Question

I have a <206x193> matrix A. It contains the values of a parameter at 206 different locations at 193 time steps. I am interested in the maximum value at each location over all times as well as the corresponding indices. I have another matrix B with the same dimensions of A and I'm interested in values for each location at the time that A's value at that location was maximal.

I've tried [max_val pos] = max(A,[],2), which gives the right maximum values, but A(pos) does not equal max_val.

How exactly does this function work?

I tried a smaller example as well. Still I don't understand the meaning of the indices....

>> H

H(:,:,1) =

     1     2
     3     4

H(:,:,2) =

     5     6
     7     8

>> [val pos] = max(H,[],2)

val(:,:,1) =

     2
     4

val(:,:,2) =

     6
     8

pos(:,:,1) =

     2
     2

pos(:,:,2) =

     2
     2
Was it helpful?

Solution

The indices in idx represent the index of the max value in the corresponding row. You can use sub2ind to create a linear index if you want to test if A(pos)=max_val

A=rand(206, 193);
[max_val, idx]=max(A, [], 2);
A_max=A(sub2ind(size(A), (1:size(A,1))', idx));

Similarly, you can access the values of B with:

B_Amax=B(sub2ind(size(A), (1:size(A,1))', idx));

From your example:

H(:,:,2) =

 5     6
 7     8

[val pos] = max(H,[],2)

val(:,:,2) =

 6
 8

pos(:,:,2) =

 2
 2

The reason why pos(:,:,2) is [2; 2] is because the maximum is at position 2 for both rows.

OTHER TIPS

max is a primarily intended for use with vectors. In normal mode, even the multi-dimensional arrays are treated as a series of vectors along which the max function is applied.

So, to get the values in B at each location at the time where A is maximum, you should

// find the maximum values and positions in A
[c,i] = max(A, [], 2);
// iterate along the first dimension, to retrieve the corresponding values in B
C = [];
for k=1:size(A,1)
    C(k) = B(k,i(k));
end

You can refer to @Jigg's answer for a more concise way of creating matrix C

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top