I have data in 3D array and I know indices in the first two dimensions. How do I collect all data without for loop?

2 次查看(过去 30 天)
For example
Data(:,:,1) = [1,2,3
4,5,6
7,8,9];
Data(:,:,2) = [11,22,33
44,55,66
77,88,99];
I expect the output to be output(:,:,1) = [1,3
7,5]
output(:,:,2) = [11,33
77,55]
I know that the index are idxRow = [1,1
3,2];
idxCol = [1,3
1,2];
How do I use idxRow and idxCol to extract everything from Data?

回答(1 个)

Matt J
Matt J 2023-5-18
编辑:Matt J 2023-5-18
One way
Data(:,:,1) = [1,2,3
4,5,6
7,8,9];
Data(:,:,2) = [11,22,33
44,55,66
77,88,99];
idxRow = [1,1
3,2];
idxCol = [1,3
1,2];
[m,n,p]=size(Data);
idx=sub2ind([m,n],idxRow,idxCol);
D=reshape(Data,[],p);
output = reshape(D(idx,:),[size(idxRow),p])
output =
output(:,:,1) = 1 3 7 5 output(:,:,2) = 11 33 77 55

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by