Indexing into a multidemesional array using a multidimensional array
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Kevin McAughey
am 18 Nov. 2016
Kommentiert: Guillaume
am 18 Nov. 2016
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
0 Kommentare
Akzeptierte Antwort
Guillaume
am 18 Nov. 2016
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 Kommentare
Guillaume
am 18 Nov. 2016
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.
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!