Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 14126

Generate triangular matrix of cumulative products efficiently

$
0
0

Take a 1D vector, for example [a b c d].

Then build the following matrix

a    0   0  0ab   b   0  0abc  bc  c  0abcd bcd cd d

The code I got so far does the job, but it's ugly and has a for loop which should be completely unnecessary.

import numpy as npv = np.array([1, 2, 3])n = len(v)matrix = np.zeros((n,n))for i in range(n):    matrix [i,:i+1] = np.flip(np.cumprod(np.flip(v[:i+1])))print(matrix)# [[1. 0. 0.]#  [2. 2. 0.]#  [6. 6. 3.]]

How can I vectorise it?


Viewing all articles
Browse latest Browse all 14126

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>