wot
wot

Reputation: 369

adding numpy vector to a numpy multi-dimensional array

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 :-(

Upvotes: 1

Views: 2020

Answers (2)

Fred Foo
Fred Foo

Reputation: 363637

Try this. Allocate the matrix, here zero-initialized for effect:

>>> import numpy as np
>>> fmatrix = np.zeros((50, 1000))

Then index into it to obtain fvector:

>>> fvector = fmatrix[0]

Then assign to fvector's elements:

>>> for i in xrange(1000):
...     fvector[i] = i

If you now inspect fmatrix[0], the first row of fmatrix, you'll find that it has been assigned to in the previous loop. That's because the NumPy row indexing creates fvector as a view on fmatrix's first row. This saves you a copy.

Upvotes: 1

unutbu
unutbu

Reputation: 879939

fvector has shape (1,1000). That's a 2D array, even if one axis has length 1. You can slice it down to a 1D array with fvector[0,:]. This gives the first row.

fmatrix has shape (50,1000). You can slice it down to a 1D array with fmatrix[i,:]. This gives the ith row.

So to assign the values in the first row of fvector to the ith row of fmatrix:

fmatrix[i,:] = fvector[0,:]

Perhaps however there is no need for fvector to be a 2D array? Perhaps just make it a 1D array to begin with:

fvector = np.empty(1000)
for i in range(0, 1000):
    fvector[i] = function_value

and then you could do the assignment with

fmatrix[i,:] = fvector

Upvotes: 1

Related Questions