Arg max without using a loop

1 Ansicht (letzte 30 Tage)
Luca Gagliardone
Luca Gagliardone am 8 Aug. 2017
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

Akzeptierte Antwort

Adam
Adam am 8 Aug. 2017
Bearbeitet: Adam am 8 Aug. 2017
[ 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.

Weitere Antworten (1)

Luca Gagliardone
Luca Gagliardone am 8 Aug. 2017
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 Kommentare
Adam
Adam am 8 Aug. 2017
Well, everything is linear indexing under the hood anyway.
Luca Gagliardone
Luca Gagliardone am 9 Aug. 2017
Well, that's true!

Melden Sie sich an, um zu kommentieren.

Kategorien

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

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by