Indexing into a multidemesional array using a multidimensional array

This question seems similar to a previously answered question, but I'm not sure if the answer there applies to my problem.
I have an array, X, which has dimensions k by m by n and I have another array, Y, with indices for the first dimension k, which has dimensions m by n. I want to create an output matrix of m by n of each value of X in the k dimension where the index in that k dimension corresponds to the value in Y for each value of m and n.
I know that is a bit confusing, but in essence I want to achieve the following code via clever application of indexing, rather than using nested for loops.
m = size(X,2);
n = size(X,3);
for m_count = 1:length(m)
for n_count = 1:length(n)
output(m_count,n_count) = X(Y(m_count,n_count),m_count,n_count)
end
end

 채택된 답변

Guillaume
Guillaume 2016년 11월 18일
I think it should rather be:
[rows, columns] = ndgrid(1:size(Y, 1), 1:size(Y, 2));
output = X(sub2ind(size(X), Y, rows, columns))

댓글 수: 2

This seems to work perfectly, now I'll just have to look through it so that I can understand why!
rows and columns are just two matrices corresponding to the row and column indices of the corresponding elements of Y.
sub2ind converts these three coordinate matrices into a single linear index which can be used to index X.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2016년 11월 18일
편집: Jan 2016년 11월 18일
Try this:
output = X(sub2ind(size(X), Y(:), 1:size(x,2), 1:size(x,3))

댓글 수: 1

When I tried this it threw the following error:
Error using sub2ind (line 51)
The subscript vectors must all be of the same size.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

질문:

2016년 11월 18일

댓글:

2016년 11월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by