Get second max element in matlab

I have an array, say A = [ 3 5 6 7 ] . I know that I can get the maximum value of this array using max(A) and it returns 7 , but how can I get the second maximum ( 6 ) from this array without sorting or deleting the first maximum value?

+4
source share
3 answers

I can offer the following complex solution:

 second_max_value = max(A(A~=max(A))) 

Here A(A~=max(A)) will be a temporary array that does not contain the maximum value of the original array. Than you get the maximum of this array.

+7
source

First of all, if you do not have really large vectors, use a unique one and get the second last index.

If you want to save the max element, and the vector does not contain NaN, you can try:

 [max_value,max_idx] = max(A); % [3 5 6 7] A(idx) = NaN; % [3 5 6 NaN] second_max_value = max(A); % 6 A(idx) = max_value; % [3 5 6 7] 

If you have multiple indexes with the same maximum value, you can enable

 if length(max_idx)>1, second_max_value=max_value, end 

UPDATE:

According to the OP comment next to the question, let me add:

You can also use sort without changing the original array:

 [~, idx] = sort(A); A(idx(1)) % is the max value A(idx(2)) % is the second max value 
+5
source

What about

  B = unique(A); % // Finds unique values and sorts max_2 = B(end-1); % // Second maximum 

?

Test:

  A= [ 3 5 6 7 2 4] B = unique(A) B(end-1) ans = 6 
+2
source

All Articles