matlab indexing 3D array -


suppose construct following 3d array

n = 3; = zeros(n,n,n); a(1:n^3) = 1:n^3; 

which gives

>>  a(:,:,1) =   1     4     7  2     5     8  3     6     9  a(:,:,2) =  10    13    16 11    14    17 12    15    18  a(:,:,3) =  19    22    25 20    23    26 21    24    27 

one can see how matlab indexes 3d array above example. suppose access (ii = 1, jj = 3, kk = 2) element of array, can done by

>>a(1,3,2)  ans =  16 

alternatively, can use following form based on matlab indexing rule demonstrated above

a(ii + (jj-1)*n + (kk-1)*n^2) 

as example, ii = 1, jj = 3, kk = 2, get

>>  a(1 + (3-1)*3 + (2-1)*3^2)  ans =  16 

to illustrate problem, define following 3d meshgrid (say purpose of index manupulations not relevant here):

[j1 j2 j3] = meshgrid(1:n); 

if not wrong, common sense expect

a(j1 + (j2-1)*n +(j3-1)*n^2) 

to give me same matrix based on above discussions, get

>> a(j1 + (j2-1)*3 +(j3-1)*3^2)  ans(:,:,1) =   1     2     3  4     5     6  7     8     9  ans(:,:,2) =  10    11    12 13    14    15 16    17    18  ans(:,:,3) =  19    20    21 22    23    24 25    26    27 

from see if want same 3d array need use

>> a(j2 + (j1-1)*3 +(j3-1)*3^2) 

which strange me. posting issue here see other people think this.

there unconventional thing in matlab, order of axis [y,x,z]. y first axis, x second. meshgrid returns [x,y,z] must use:

[j2 j1 j3] = meshgrid(1:n); 

then expected result. alternatively can switch ndgrid returns dimensions in order:

[j1 j2 j3] = ndgrid(1:n); 

Comments