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
Hi, i want to take multiple points from a 3d array, but i don't know any efficient methods without using loops. I've tried messing around with sub2ind but it doesn't seem very effective to do each 2d matrix separately.
If you want all values of the data in the third dimension you can easily acess it with:
Rows = [4, 1, 3] Col = [1, 2 ,3]
val(Rows,Col,:)
Output:
>> 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
You can obtain the desired output with:
x1 = [4,1,3];
x2 = [1,2,3];
x = val(x1,x2,:);
for ii = 1:size(val,3)
res(:,:,ii) = diag(x(:,:,ii)).';
end
Output:
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
Or with sub2ind
, and implicit expansion (matlab 2016b and newer)
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
Output:
res =
0.779100 0.715000 0.030500
0.576700 0.182900 0.978700
0.096700 0.818100 0.973000
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.