在 matlab 中访问 3D 矩阵中的多个元素


val(:,:,1) =
0.1068    0.7150    0.6987    0.5000
0.6538    0.9037    0.1978    0.4799
0.4942    0.8909    0.0305    0.9047
0.7791    0.3342    0.7441    0.6099

val(:,:,2) =
0.6177    0.1829    0.4899    0.5005
0.8594    0.2399    0.1679    0.4711
0.8055    0.8865    0.9787    0.0596
0.5767    0.0287    0.7127    0.6820

val(:,:,3) =
0.0424    0.8181    0.6596    0.8003
0.0714    0.8175    0.5186    0.4538
0.5216    0.7224    0.9730    0.4324
0.0967    0.1499    0.6490    0.8253
Row Col    
4   1
1   2
3   3

嗨,我想从 3D 数组中获取多个点,但我不知道不使用循环的任何有效方法。我尝试过弄乱sub2ind,但分别执行每个2d矩阵似乎不是很有效。

如果您希望数据的所有值都在第三维中,您可以使用以下方法轻松获得它:

Rows = [4, 1, 3] Col = [1, 2 ,3]
val(Rows,Col,:)

输出:

>> val([4, 1, 3],[1, 2, 3],:)
ans(:,:,1) =
0.7791 0.3342 0.7441 0.1068 0.7150 0.6987 0.4942 0.8909 0.0305
ans(:,:,2) =
0.5767 0.0287 0.7127 0.6177 0.1829 0.4899 0.8055 0.8865 0.9787
ans(:,:,3) =
0.0967 0.1499 0.6490 0.0424 0.8181 0.6596 0.5216 0.7224 0.9730

您可以通过以下方式获得所需的输出:

x1 = [4,1,3];
x2 = [1,2,3];
x = val(x1,x2,:);
for ii = 1:size(val,3)
res(:,:,ii) = diag(x(:,:,ii)).';
end

输出:

res =
ans(:,:,1) =
0.779100   0.715000   0.030500
ans(:,:,2) =
0.57670   0.18290   0.97870
ans(:,:,3) =
0.096700   0.818100   0.973000

或者使用sub2ind和隐式扩展(matlab 2016b 及更高版本(

x1 = [4,1,3];
x2 = [1,2,3];
len = length(x1);
ind = sub2ind(size(val),x1+zeros(len,1),x2+zeros(len,1),[1:size(val,3)].'+zeros(1,len));
res = A(ind)
%if you want to preserve the third dimension add: permute(res,[1,3,2])
%we can do that because an array in matlab has an infinite number of singleton dimension

输出:

res =
0.779100   0.715000   0.030500
0.576700   0.182900   0.978700
0.096700   0.818100   0.973000

最新更新