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

4 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Walter Roberson
Walter Roberson il 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 Commenti
Jose Ramon Silos de Alba
Jose Ramon Silos de Alba il 19 Feb 2018
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 il 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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by