Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

How to find second largest value in an array?

Asked by Minu

Minu (view profile)

on 7 Jun 2013
Latest activity Answered by Fernando

Fernando (view profile)

on 17 Nov 2014

Hi

I want to find the second largest and minimum value in array? A=[1;10;15;30;40;50;100].I want to get the result as Second minimum value=10 and second largest value=50 Help me plz...

1 Comment

Walter Roberson

Walter Roberson (view profile)

on 7 Jun 2013

What do you want to do if there are multiple instances of the maximum or minimum?

Minu

Minu (view profile)

Tags

Products

No products are associated with this question.

3 Answers

Answer by Andrei Bobrov

Andrei Bobrov (view profile)

on 7 Jun 2013
Edited by Andrei Bobrov

Andrei Bobrov (view profile)

on 7 Jun 2013
Accepted answer
[ii,ii] = sort(A);
out = A(ii([2,end-1]));

for your example (A) just:

out = A([2,end-1]);

more variant

A1 = unique(A);
out = A1([2,end-1]);

4 Comments

Jan Simon

Jan Simon (view profile)

on 7 Jun 2013

The sorting can be more expensive than searching the max twice:

[ignore, index] = max(A);
A(index) = -Inf;       % [EDITED], not +Inf!
max2 = max(A);

In this method Walter's suggestions must be considered also.

Walter Roberson

Walter Roberson (view profile)

on 7 Jun 2013

If the array is single precision or double precision, NaN is safer than Inf as there might be Inf in the array.

If the array is any of the other numeric data types, Inf will not exist and will be treated as the maximum numeric value for that datatype.

Jan Simon

Jan Simon (view profile)

on 7 Jun 2013

Ficed typo: Of course -Inf is needed instead of +Inf to mask an existing maximium.

@Walter: Exactly. While the original message "A=[1;10;15;30;40;50;100]" looks like the OP talks about a double vector with finite values, the another type of input or values must be considered.

Even if another value is -Inf, my method replies the correct result. But NaN is the better choice.

Andrei Bobrov

Andrei Bobrov (view profile)

Answer by Walter Roberson

Walter Roberson (view profile)

on 7 Jun 2013
for K = A
  if sum(A > K) == 1
    disp(K)
  end
end

1 Comment

per isakson

per isakson (view profile)

on 7 Jun 2013

I got your point.

Walter Roberson

Walter Roberson (view profile)

Answer by Fernando

Fernando (view profile)

on 17 Nov 2014

function [ y ] = second_min( x )

 y = min(x(x>min(x)));

end

&

function [ y ] = second_max( x )

 y = max(x(x<max(x)));

end

0 Comments

Fernando

Fernando (view profile)

Contact us