简体   繁体   中英

matlab indexing 3D array

Suppose I construct the following 3D array

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

which gives

>> A

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 a 3D array from the above example. Suppose I would like to access (ii = 1, jj = 3, kk = 2) element of this array, which can be done by

>>A(1,3,2)

ans =

16

Alternatively, I can use the following form based on the matlab indexing rule demonstrated above

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

as an example, for ii = 1, jj = 3, kk = 2, I get

>>  A(1 + (3-1)*3 + (2-1)*3^2)

ans =

16

To illustrate the problem, I define the following 3D meshgrid (say for the purpose of index manupulations which is not relevant here):

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

If I am not wrong, common sense would expect that

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

to give me the same matrix based on the above discussions, but I 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 this I see that if you want to get the same 3D array you actually need to use

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

which is very strange to me. I am posting this issue here to see what other people think about this.

There is a unconventional thing in matlab, the order of axis is [Y,X,Z]. Y is the first axis, X the second. As meshgrid returns [X,Y,Z] you must use:

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

Then you get the expected result. Alternatively you can switch to ndgrid which returns the dimensions in order:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM