Multi-dimensional array indexing
5 views (last 30 days)
Show older comments
I have a matrix of stored values and am trying to use a second matrix to access the indices of the values that I need.
For example,
A = randi([0 100],3,126); B = [1 27 88; 10 37 53; 7 19 76];
Where each row of B corresponds to indices of each row of A I would like the values from. What is the best way to approach this problem?
0 Comments
Answers (1)
Walter Roberson
on 14 Apr 2018
This is one of those cases where you can vectorize the code, but doing so will be hard to read and likely less efficient than a loop.
The vectorized version of your code is, for R2016b or later:
A((B-1).*size(A,1)+(1:size(A,1)).')
For R2016a or earlier,
A(bsxfun(@plus, (B-1).*size(A,1), (1:size(A,1)).'))
You can see that this involves creating multiple temporary matrices the size of your index, and several mathematical calculations that have no obvious meaning.
For small arrays, this is clearly premature optimization: a case where something that might maybe faster but more complicated has been substituted for something clear, when the code was never going to occupy much computation time anyhow, and the human costs of reading and debugging the code are going to far out-weigh any computation time saved.
For larger arrays... well, this can actually turn out to take more time than using a loop, because of the large temporary arrays needed.
0 Comments
See Also
Categories
Find more on Multidimensional Arrays 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!