Reputation: 13
I have a matrix as follow.
octave:63> a
a =
ans(:,:,1) =
0.411710 0.947670
0.068291 0.368340
ans(:,:,2) =
0.27178 0.56699
0.54317 0.27393
ans(:,:,3) =
0.72621 0.44131
0.22743 0.61914
Using max function, I can get the index of maximum value based on certain dimension.
octave:64> [a2_val a2_indx] = max(a, [], 2)
a2_indx =
ans(:,:,1) =
2
2
ans(:,:,2) =
2
1
ans(:,:,3) =
1
2
If I have the same matrix as a with zero values, is there any way I can mark the maximum location with 1? Something like follow.
octave:65> z
z =
ans(:,:,1) =
0 1
0 1
ans(:,:,2) =
0 1
1 0
ans(:,:,3) =
1 0
0 1
I prefer the solution to be dimension-free like the max function capable of.
Thanks.
Upvotes: 1
Views: 525
Reputation: 23455
Simplest way is probably to replicate the max matrix along that dimension and use logical comparison:
dim = 2; % The dimension along which we max
% Prep a size matrix for the replication
dims = ones( size( size( a ) ) );
dims( dim ) = size( a, dim ); % (all ones except the
% dimension that gets maxed)
result = ( a == repmat( max( a, [], dim ), dims ) )
Upvotes: 1