Use multidimensional Indices returned by max to get values from another array of same size

조회 수: 2 (최근 30일)
I have a three dimensional array and I find the maximum value and indices of these values along the third dimension. How do I use these indices to find the values at the corresponding locations in another array of the same dimensions,
For example:
x = randn(5,10,20)
[xmax,ixmax]=max(x,[],3);
% ixmax is a 5 x 10 array that has the indices of the maxima along the third dimension of x
y = randn(5,10,20);
% I want to find the values of y at the locations of the maxima of x
% I can of course do it by looping
for ii = 1:5
for jj = 1:10
yxmax(ii,jj)=y(ii,jj,ixmax(ii,jj));
end
end
How do I do this without looping?

채택된 답변

Steven Lord
Steven Lord 2020년 1월 10일
If you're using release R2019a or later, specify the 'linear' option to obtain linear indices from max and use those linear indices directly to index into the other array of the same size.
rng default
x = reshape(randperm(27), [3 3 3]);
y = reshape(randperm(27), [3 3 3]);
[value, index] = max(x, [], 'linear');
Let's look at x side-by-side with y, separated by a strip of NaN values.
sideBySide = cat(2, x, NaN(3, 1, 3), y)
Look at the indices, the elements of x, and the corresponding elements of y.
I = index(:);
results = [I, x(I), y(I)]
As an example the second element in I is 4. If you look at sideBySize, the fourth element of x is 16 and the fourth element of y is 8. This is exactly what the second row of results shows.
  댓글 수: 1
JoeB
JoeB 2020년 1월 10일
This solution is preferable because it does not need a call to ndgrid. By ising the linear indexing option then one can apply the index similarly to a 1-D array. Glad to hear about this new option.
In my example this would be as follows:
x = randn(5,10,20);
y = randn(5,10,20);
[xmax,linindex] = max(x,[],3,'linear');
yxmax = y(linindex);
% test by applying index to x
xmaxtest = x(linindex);
plot(xmax,xmaxtest,'.');

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2020년 1월 10일
When you max() a 3d array along the third dimension, the 2d second output, Index, indexed at J, K is such that Array(J, K, Index(J, K)) is the location of a maximum.
You can construct
[Jgrid, Kgrid] = ndgrid(1:size(Array, 1),1:size(Array, 2));
linidx = sub2ind(size(Array), Jgrid, Kgrid, Index)) ;
And then OtherArry(linidx)
  댓글 수: 1
JoeB
JoeB 2020년 1월 10일
See below: there is now an option for max (and presumably other related functions) to return linear indexing!

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by