Asked by Minu
on 7 Jun 2013

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...

*No products are associated with this question.*

Answer by Andrei Bobrov
on 7 Jun 2013

Edited by Andrei Bobrov
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]);

Show 3 older comments

Jan Simon
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.

moon pie
on 28 Dec 2015

How to get the index with the second minimum or maximum value in an array?

Image Analyst
on 28 Dec 2015

Define second minimum. In the array [1,1,2,3] what is the second minimum? Is it 1 or is it 2?

Answer by Fernando
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

Answer by Walter Roberson
on 7 Jun 2013

for K = A if sum(A > K) == 1 disp(K) end end

per isakson
on 7 Jun 2013

I got your point.

Related Content

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

Learn moreOpportunities for recent engineering grads.

Apply Today
## 1 Comment

## Walter Roberson (view profile)

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/78278#comment_153446

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