[英]Slice a 3D matrix with a list of first-dimension indices and its corresponding second-dimension indices in MATLAB?
How do I slice a 3D matrix with a list of first-dimension indices and its corresponding second-dimension indices? 如何对具有一维索引及其对应的第二维索引列表的3D矩阵进行切片?
For example, given 例如,给定
>> A = cat(3, [1 2 3; 4 5 6; 7 8 9], [10 20 30; 40 50 60; 70 80 90], [100 200 300; 400 500 600; 700 800 900])
A(:,:,1) =
1 2 3
4 5 6
7 8 9
A(:,:,2) =
10 20 30
40 50 60
70 80 90
A(:,:,3) =
100 200 300
400 500 600
700 800 900
I want to slice out A(2, 3, :)
and A(1, 2, :)
to get [6 60 600; 2 20 200]
我想切出
A(2, 3, :)
和A(1, 2, :)
得到[6 60 600; 2 20 200]
[6 60 600; 2 20 200]
. [6 60 600; 2 20 200]
。
I failed with 我失败了
>> A([2, 1], [3, 2], :)
ans(:,:,1) =
6 5
3 2
ans(:,:,2) =
60 50
30 20
ans(:,:,3) =
600 500
300 200
I believe there's a one-liner/elegant solution. 我相信有一个单线/优雅的解决方案。
To extract the desired elements subscripts should be converted to indices ( sub2ind
), but before it a 3D transpose ( permute
) should be applied so the third dimension becomes the first. 以提取所需的元素下标应转换为索引(
sub2ind
),但在此之前它在3D转置( permute
应适用),以使第三尺寸变为第一。
idx = [2 3; 1 2];
[m n z]= size(A);
B=permute(A,[3 1 2]);
result = B(:,sub2ind([m,n],idx(:,1),idx(:,2)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.