MATLAB Answers

How to find value which is berofe max value of an array?

2 views (last 30 days)
Serhii Sheinych
Serhii Sheinych on 22 Nov 2019
Commented: Walter Roberson on 23 Nov 2019
I have an array, let it be r1 = rand(1,100).
I need to find max value and a value which is before maximum. How can i do it?
Maimum = max (r1);
p.s Simple example a = [1, 4, 10, 2, 7, 3, 6];
I know that max is 10, and 7 is before my max value. How to find 7, using Matlab?


Sign in to comment.

Accepted Answer

Bryan on 22 Nov 2019
Edited: Bryan on 22 Nov 2019
another option would be


Show 1 older comment
Walter Roberson
Walter Roberson on 22 Nov 2019
The effective difference between this solution and my solution using maxk, is that with this solution if there is a "tie" for maximum, this returns a value less than that maximum anyhow, whereas the maxk solution will return multiple copies of the same value.
Also, this version has some subtle behavior if all of the entries are nan or all except one are nan: this version will return empty, whereas the maxk version would return nan.
Walter Roberson
Walter Roberson on 23 Nov 2019
They are both valid, just slightly different on edge cases.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by