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.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
DrakonianD
  • 39
  • 2
  • 11
  • `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` – Mike Müller May 08 '16 at 08:14

3 Answers3

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
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
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]
Community
  • 1
  • 1
yelsayed
  • 5,236
  • 3
  • 27
  • 38
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]])
Sudipta Basak
  • 3,089
  • 2
  • 18
  • 14
  • Thanks a lot for the effort sudipta as yasser pointed out, it is very simple as matrix[:,:,1] bit tricky isnt it :) Thanks again. – DrakonianD May 08 '16 at 08:09