How can I index a multidimensional array with another multidimensional array containing indices into one of the dimensions of the first array?

4 Ansichten (letzte 30 Tage)
Hello everyone.
I have the following problem. Let me give an example:
Suppose I have a 4-D array A of real numbers of 10000x10x10x2. I also have a 4-D array of indices into the first dimension of A, call it I, which is of the size 4500x10x10x2. (so all values in I are integers between 1 and 10000). I need an output array B of the size 4500x10x10x2 in which the first dimension would be the indexed dimension of A applied element by element for the other 3 dimensions. What is the efficient way of doing it? A(I) does not work.
There is a also constraint on I is that every vector along the 1-st dimension (4500) has consecutive integer numbers, so, say I(:,1,1,1) could be, for example, 1,2,3,...4500; or 1000,1001,....5499. (thus I is uniquely defined by 200 values)
This can be solved with a triple nested loop over dimensions 2,3, and 4, but it is slow and I need to repeat this process many times. I can also reshape both matrices to 10000x200 and 4500x200, respectively, and use a single "for" loop over the 2-nd dimension, but still have to loop over. Is there an elegant solution for this? Maybe sub2ind can be used, but I don't see how.
Thanks a lot.

Akzeptierte Antwort

Roger Stafford
Roger Stafford am 26 Aug. 2014
[n1,n2,n3,n4] = size(I);
I2 = repmat(size(A,1)*(0:n2*n3*n4-1),n1,1);
B = reshape(A(I(:)+I2(:)),size(I));

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by