I would like to create an n by m matrix based on elements of an n + m length array.
Here a simple double for loop suffices, but I wish for an expedient solution. The matrix will be relatively small.
n = 4
m = 6
s = n + m
array = np.arange(s) # note: arange is only for example. real array varies.
matrix = np.zeros((n,m))
for i in range(n):
for j in range (m):
matrix[i,j] = array[i+j]
I have found that a comprehension is faster than the double for loops
matrix3 = [[array[i+j] for i in range(m)] for j in range(n)]
Is there a faster way?
An additional bonus would be to incorporate the modulo operator. I only actually need the indices where i+j % 2 == 0. In the double for loop the modulo method seems a little bit faster, but this may not be convenient or expedient for generating this matrix via numpy.
It is fine to not do this, since matrix multiplcation will occur after and the necessary elements will be multiplied by zero anyways. My mentioning the modulo is only in the off-case that this leads to a faster solution.
for this MWE
for i in range(n):
for j in range (m):
if (i + j) % 2 == 0:
matrix[i,j] = array[i+j]
note:
I ask for a numpy solution under the assumption numpy will be fastest, but any pure python (including numpy/scipy) solution is fine so long as it is faster than pure python double for loops
motivation:
I am trying to remove all dependencies on arrays from a double for loop so that I can use broadcasting rather than a double for loop. This is the last array left
arr[:, None]+ arr