3

When I use Python to model a 3-Dimensional matrix, I first make a multi-array of zeros. Then, I can easily overwrite each element by referencing its index. The problem is, the order of indices change when trying to reference multiple elements using [:]. I'm going to speak in matrix math jargon, so bear with me.

In the example below, I want to model the position of an object in the 2-D plane per time level. So for each time level, I have an X (row) and Y (column) coordinate. In the example below, I use two time levels with 3 rows and 4 columns.

    >>> Simple = numpy.zeros([2,3,4],float)
    >>> print Simple
    [[[ 0.  0.  0.  0.]
    [ 0.  0.  0.  0.]
    [ 0.  0.  0.  0.]]

    [[ 0.  0.  0.  0.]
    [ 0.  0.  0.  0.]
    [ 0.  0.  0.  0.]]]

Looks good. I have two 3x4 matrices. Now I want to change the value of the 2nd matrix (2nd time level), 3rd row, 4th column to be equal to 9.

    >>> Simple[1][2][3] = 9
    >>> print Simple
    [[[ 0.  0.  0.  0.]
    [ 0.  0.  0.  0.]
    [ 0.  0.  0.  0.]]

    [[ 0.  0.  0.  0.]
    [ 0.  0.  0.  0.]
    [ 0.  0.  0.  9.]]]

So far so good. From this, I can tell that the order of indices is Simple[TimeLevel,X,Y]. So now, for each time level, I want the element in the first row, second column (timelevel = both,x=0,y=1) to be the number "4".

   >>> Simple[:][0][1] = 4
   >>> print Simple
   [[[ 0.  0.  0.  0.]
   [ 4.  4.  4.  4.]
   [ 0.  0.  0.  0.]]

   [[ 0.  0.  0.  0.]
   [ 0.  0.  0.  0.]
   [ 0.  0.  0.  9.]]]

So as you can see, the order of indices is no longer the same. It switched from Simple[TimeLevel,row,column] to Simple[column,TimeLevel,row].

My question is: WHY?

1 Answer 1

2

All [:] does is return a copy of the sequence. This is not what you want.

>>> Simple[:,0,1] = 4
>>> Simple
array([[[ 0.,  4.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]],

       [[ 0.,  4.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]]])
Sign up to request clarification or add additional context in comments.

Comments

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.