I have a loop that adds elements to a 1d array:
for i in range(0, 1000):
fvector[0, i] = function_value
after the loop finishes, I have a 1 x 1000 vector that I want to store in a multi-dimensional array fmatrix, which is 50 x 1000. I managed to do this using a loop and copying each element individually – but it is very slow. I’ve then tried to use slice to copy the whole vector in one go after the loop and then be ready to copy next vector at the next column. How do I make it go to the next column? I’ve tried:
s=slice([i], None)
fmatrix[s] = fvector
and various combinations for s, but I get error messages about setting an array element with a sequence, or invalid syntax.
I know this should be straight forward but I’m very new to python, numpy and arrays 🙁
Try this. Allocate the matrix, here zero-initialized for effect:
Then index into it to obtain
fvector:Then assign to
fvector‘s elements:If you now inspect
fmatrix[0], the first row offmatrix, you’ll find that it has been assigned to in the previous loop. That’s because the NumPy row indexing createsfvectoras a view onfmatrix‘s first row. This saves you a copy.