Maximizing along n-1 dimensions of an n-dimensional array without a for loop

I have an n-dimensional array, VV, which I would like to maximize along all dimensions for each element in the first dimension. I would also like to obtain the associated linear indices so that I can evaluate related arrays at those locations. I have to do this a large amount of times, so I need to figure out a way to do this without a for loop.
Here is an example for an n=3 dimensional array, but with a loop:
VV=rand(10,10,10);
for ii=1:size(VV,1)
Vtemp = squeeze(VV(ii,:,:));
[V(ii) I(ii)] = max(Vtemp(:));
end
[~,ind] = ismember(V,VV);
Any help would be appreciated.

 채택된 답변

Jan
Jan 2021년 10월 12일
편집: Jan 2021년 10월 12일
VV = rand(8, 9, 10);
for ii = 1:size(VV,1)
Vtemp = squeeze(VV(ii, :, :));
[V(ii), I(ii)] = max(Vtemp(:));
end
[~,ind] = ismember(V, VV);
ind
ind = 1×10
1161 12 293 1004 415 746 307 1228 479 620
s = size(VV, 1);
W = reshape(VV, s, []);
[maxV, Index] = max(W, [], 2);
ind2 = sub2ind(size(W), 1:s, Index.')
ind2 = 1×10
1161 12 293 1004 415 746 307 1228 479 620

추가 답변 (1개)

VV=randi(1000, 5, 5, 5);
[values, locations] = max(VV, [], 1:ndims(VV)-1, 'linear');
check = [reshape(values, [], 1), reshape(VV(locations), [], 1)]
check = 5×2
904 904 984 984 973 973 981 981 975 975

댓글 수: 1

Thanks for pointing to the new 'linear' output. It was introduced in R2019a.

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

카테고리

도움말 센터File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

질문:

2021년 10월 12일

댓글:

Jan
2021년 10월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by