Arg max without using a loop

조회 수: 5 (최근 30일)
Luca Gagliardone
Luca Gagliardone 2017년 8월 8일
댓글: Luca Gagliardone 2017년 8월 9일
I am looking for a method to reproduce the following without using a loop.
The issues come from the fact that the matrices I am using are too big and I could save some space avoiding to create a third matrix C to do the job.
My aim is to find some function f that does something similar to B = f(B(policy)). Is it possible to do it?
A = rand(10,20,30);
B = rand(10,20,30);
[A_hat, policy] = max(A,[],3);
for i = 1:10
for ii = 1:20
C = B(i,ii,policy(i,ii));
end
end
Thanks for the attention.
Sincerely
Luca

채택된 답변

Adam
Adam 2017년 8월 8일
편집: Adam 2017년 8월 8일
[ rowGrid, columnGrid ] = ndgrid( 1:size(A,1), 1:size(A,2) );
idx = sub2ind( size( B ), rowGrid, columnGrid, policy );
C = B( idx );
As far as I am aware you have to convert to linear indices to extract the data as above. I have done exactly this for something I am working on recently. There may be a more efficient way, but not that I am aware of.
I tested one or two values to check they were correct and also looking at
A( idx )
gives a good confidence level too since these numbers are obviously all towards the higher end of the 0-1 range, e.g.
>> stuff = A( idx );
>> mean( stuff(:) )
ans =
0.969286594713116
Note: This may be memory intensive though as you create two grids of size(A,1) * size(A,2) containing the row and column indices in order to be able to turn all your 3rd dimension indices into linear indices.

추가 답변 (1개)

Luca Gagliardone
Luca Gagliardone 2017년 8월 8일
Thanks Adam, I see your point.
It still seems to me impossible that Matlab does not provide a more direct way without recurring to linear indexing (which is also quite RAM-expensive with ndgrid). I will wait for a few days before accepting definitely your answer, hoping for an easier solution!
Thanks again for your help.
Luca
  댓글 수: 2
Adam
Adam 2017년 8월 8일
Well, everything is linear indexing under the hood anyway.
Luca Gagliardone
Luca Gagliardone 2017년 8월 9일
Well, that's true!

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

카테고리

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