How to get values from a 3D Matrix in a single step

4 次查看(过去 30 天)
AA is a 3D matrix containing info, MatrixIdx is a 2D Matrix. Would like to know if there is a single step way to do this, such as Value(:,:) = AA(something,something,MatrixIdx)
for jj=1:size(AA,1)
for kk =1:size(AA,2)
Value(jj,kk) = AA(jj,kk,MatrixIdx(jj,kk));
end
end

采纳的回答

Walter Roberson
Walter Roberson 2018-2-18
nrow = size(AA,1);
ncol = size(AA,2);
[JJ, KK] = ndgrid(1:nrow, 1:ncol);
Value = AA( sub2ind(JJ, KK, MatrixIdx(1:nrow, 1:ncol)) );
  2 个评论
Jose Ramon Silos de Alba
Thank you Walter, I'm guessing this is significantly faster than the for loops. Right? Definitely checking the ndgrid and sub2ind functions
Walter Roberson
Walter Roberson 2018-2-20
"I'm guessing this is significantly faster than the for loops. Right?"
No, I would not expect so. You have changed the JIT-optimizable for-loop into a call to a .m function that has to do error checking and which uses for-loops internally, and which has to calculate a bunch of linear indices. If your array sizes are large enough that the lack of vectorization in the for loop is making a significant difference, then you should be wondering whether calculating all of those linear indices and passing them around is going to be become a memory burden and lead to unnecessary steps. I have seen too many times when people want to switch to vectorizing access in these kinds of situations because the for loop is suspected of being too expensive, only to have it turn out that the amount of memory required for the indices pushes them over into swapping.
The sub2ind() can be rewritten in vectorized form without any function calls and without any for loop, but with a decided loss of clarity of what the code does. Indeed, I wrote it in vectorized form first, but then decided that it was too much trouble to explain what it was doing and switched it to the sub2ind version.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by