How to get values from a 3D Matrix in a single step
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Jose Ramon Silos de Alba
el 18 de Feb. de 2018
Comentada: Walter Roberson
el 20 de Feb. de 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 comentarios
Respuesta aceptada
Walter Roberson
el 18 de Feb. de 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 comentarios
Walter Roberson
el 20 de Feb. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!