Say I have initialized an array in 3D as:
arr_3d = np.zeros((100, 100, 100))
Now I want to change the elements at subscript indices (i, j, k)
of arr_3d
to some value (say 1), where i, j, k
are the list (or array) of indices with sizes 100, 100, 40
, respectively, along the three axes. I have tried arr_3d[i, j, k] = 1
, but it throws an error. I have tried converting the subscript indices to linear indices by np.ravel_multi_index()
, but it looks like it can't convert the subscript indices of a 3D array.
The above issue is easy to solve in Matlab, where using arr_3d(i, j, k) = 1
works.
Try it with different dimensions,ones that are distinct
In [1375]: a=np.zeros((2, 3, 4))
In [1376]: a[np.ix_([0], [1,2], [0,1])] = 1
In [1377]: a
Out[1377]:
array([[[ 0., 0., 0., 0.],
[ 1., 1., 0., 0.],
[ 1., 1., 0., 0.]],
[[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]]])
numpy
divides the array in to 'planes' on the first dimension; MATLAB does it on the last. So this shows 2 planes or blocks, each 3x4.
In octave
>> a = zeros(2,3,4);
>> a([1],[2,3],[1,2]) = 1
a =
ans(:,:,1) =
0 1 1
0 0 0
ans(:,:,2) =
0 1 1
0 0 0
ans(:,:,3) =
0 0 0
0 0 0
ans(:,:,4) =
0 0 0
0 0 0
4 blocks of 2x3.