1

I have a problem with printing a column in a numpy 3D Matrix. Here is a simplified version of the problem:

import numpy as np
Matrix = np.zeros(((10,9,3))) # Creates a 10 x 9 x 3 3D matrix
Matrix[2][2][6] = 578
# I want to print Matrix[2][x][6] for x in range(9)
# the purpose of this is that I want to get all the Values in Matrix[2][x][6]

Much appreciated if you guys can help me out. Thanks in advance.

1
  • Matrix[2][2][6] = 578 gives an IndexError because your last dimension is not big enough for the index 6. This would work Matrix[6][2][2] = 578 Commented May 8, 2016 at 8:14

3 Answers 3

3

Slicing would work:

a = np.zeros((10, 9, 3))
a[6, 2, 2] = 578
for x in a[6, :, 2]:
    print(x)

Output:

0.0
0.0
578.0
0.0
0.0
0.0
0.0
0.0
0.0
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot mike :)
1

Not sure if Numpy supports this, but you can do it with normal lists this way:

If you have three lists a = [1,2,3], b = [4,5,6], and c = [7,8,9], you can get the second dimension [2,5,8] for example by doing

list(zip(a,b,c))[1]

EDIT:

Turns out this is pretty simple in Numpy. According to this thread you can just do:

Matrix[:,1]

1 Comment

Thanks a lot Yasser You made my day :D
1

No sure if this is what you want. Here is demo:

In [1]: x = np.random.randint(0, 20, size=(4, 5, 3))

In [2]: x
Out[2]: 
array([[[ 5, 13,  9],
        [ 8, 16,  5],
        [15, 17,  1],
        [ 6, 14,  5],
        [11, 13,  9]],

       [[ 5,  8,  0],
        [ 8, 15,  5],
        [ 9,  2, 13],
        [18,  4, 14],
        [ 8,  3, 13]],

       [[ 3,  7,  4],
        [15, 11,  6],
        [ 7,  8, 14],
        [12,  8, 18],
        [ 4,  2,  8]],

       [[10,  1, 16],
        [ 5,  2,  1],
        [11, 12, 13],
        [11,  9,  1],
        [14,  5,  1]]])

In [4]: x[:, 2, :]
Out[4]: 
array([[15, 17,  1],
       [ 9,  2, 13],
       [ 7,  8, 14],
       [11, 12, 13]])

1 Comment

Thanks a lot for the effort sudipta as yasser pointed out, it is very simple as matrix[:,:,1] bit tricky isnt it :) Thanks again.

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.