Multi-dimensional array indexing
조회 수: 1 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Walter Roberson
2018년 4월 14일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!