[英]matlab indexing 3D array
Suppose I construct the following 3D array假设我构造了以下 3D 数组
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.可以从上面的示例中看到 matlab 如何索引 3D 数组。 Suppose I would like to access (ii = 1, jj = 3, kk = 2) element of this array, which can be done by
假设我想访问这个数组的 (ii = 1, jj = 3, kk = 2) 元素,这可以通过
>>A(1,3,2)
ans =
16
Alternatively, I can use the following form based on the matlab indexing rule demonstrated above或者,我可以根据上面演示的 matlab 索引规则使用以下形式
A(ii + (jj-1)*n + (kk-1)*n^2)
as an example, for ii = 1, jj = 3, kk = 2, I get例如,对于 ii = 1, jj = 3, kk = 2, 我得到
>> 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):为了说明这个问题,我定义了以下 3D 网格(例如为了索引操作,这里不相关):
[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由此我看到,如果你想获得相同的 3D 数组,你实际上需要使用
>> 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]. matlab中有一个非常规的东西,轴的顺序是[Y,X,Z]。 Y is the first axis, X the second.
Y 是第一个轴,X 是第二个轴。 As meshgrid returns [X,Y,Z] you must use:
当 meshgrid 返回 [X,Y,Z] 时,您必须使用:
[j2 j1 j3] = meshgrid(1:n);
Then you get the expected result.然后你会得到预期的结果。 Alternatively you can switch to
ndgrid
which returns the dimensions in order:或者,您可以切换到
ndgrid
,它按顺序返回尺寸:
[j1 j2 j3] = ndgrid(1:n);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.