1

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

2 Answers 2

1

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.

2
  • How do I move onto fmatrix[1] and then all the way to the last row without getting an 'index out of bounds error? Commented Dec 29, 2011 at 15:22
  • @wot: you can loop over the rows with for fvector in fmatrix; no need for indexing. Commented Dec 29, 2011 at 15:52
1

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
2
  • Thanks - I realise my confusion about 1d - 2d arrays is probably causing problems elsewhere too. Commented Dec 29, 2011 at 12:46
  • I went back and changed my 2D arrays to 1D and that really helped with the assignment syntax. I used larsmans 'view' feature for populating the matrix. So huge thanks to both. Commented Dec 30, 2011 at 11:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.