Reputation: 8670
I have an array, say A = [ 3 5 6 7 ]
. I know I can get the maximum value of this array with max(A)
and it returns 7
, but how can I get the second max (6
) from this array without sorting or removing the first maximum value?
Upvotes: 4
Views: 23137
Reputation: 12514
First of all, unless you have really-really large vectors, use unique and get the second last index.
If you wish to preserve the max element and you vector does not contain NaN's 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 indices with the same max value, it is your choice to include
if length(max_idx)>1, second_max_value=max_value, end
UPDATE:
According to the comment of the OP next to the question, let me add:
You can also use sort without changing the original array:
[~, idx] = sort(A);
A(idx(end)) % is the max value
A(idx(end-1)) % is the second max value
Upvotes: 7
Reputation: 1241
I can propose following tricky solution:
second_max_value = max(A(A~=max(A)))
Here A(A~=max(A))
will be temporary array that not contain maximal value of original array. Than you receive maximum of this array.
Upvotes: 8
Reputation: 8391
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
Upvotes: 2