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矩阵的处理似乎并不十分有效。
答案 0 :(得分:0)
如果要获取三维数据的所有值,可以使用以下方法轻松访问:
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
答案 1 :(得分:0)
您可以通过以下方式获得所需的输出:
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