How to get values from a 3D Matrix in a single step
4 views (last 30 days)
Show older comments
Jose Ramon Silos de Alba
on 18 Feb 2018
Commented: Walter Roberson
on 20 Feb 2018
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
0 Comments
Accepted Answer
Walter Roberson
on 18 Feb 2018
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 Comments
Walter Roberson
on 20 Feb 2018
"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.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!