How to index within an array using another array?

10 views (last 30 days)
I have an array 'A' of vectors of length 3 stored in a 5D matrix of size 'mXnXoXpX3'. Then, I define arrays B and C, such that:
B = sum(A.*A, 5); % Magnitude of the vectors
[~, C] = max(B, [], 1); % Location of the maximum vector magnitude along the first dimension
Here, C is of the size 1XnXoXp, and contains the location of maximum amplitudes of A, which is calculated in B. Now I wish to store these vectors (as identified in C) in a matrix D:
for i = 1 : n
for j = 1 : o
for k = 1 : p
D(1, i, j, k, :) = A(C(1, i, j, k), i, j, k, :);
end
end
end
I am wondering if there is a better way to get 'D'? Perhaps without using the for loops?

Answers (1)

Walter Roberson
Walter Roberson on 29 Jan 2016
Edited: Walter Roberson on 29 Jan 2016
As = size(A);
CAs = cumprod(As);
[I,J,K,L] = ndgrid(1:n, 1:m, 1:o, 1:p);
Aidx = squeeze(C(1,:,:,:)) + (I-1)*CAs(1) + (J-1)*CAs(2) + (K-1)*CAs(3) + (L-1)*CAs(4);
D1 = A(Aidx);
D(1,:,:,:,:) = D1;
If the first dimension of D is to be singular, then the last two statements could instead be
D = reshape(A(Aidx), 1, n, m, o, p);
Equivalently,
Aidx = sub2ind(size(A), squeeze(C(1,:,:,:)), I, J, K, L);
D = reshape(A(Aidx), 1, n, m, o, p);
  1 Comment
DK
DK on 29 Jan 2016
Sorry about an error in the subscripts. Edited it. Please see if that changes anything in your response.

Sign in to comment.

Products

Community Treasure Hunt

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

Start Hunting!