second maximum- not returning index
Show older comments
Used the following code:
function [i,y] = second_max( x )
[a,b]=max(x)
[i,y] = max(x(x==a))
end
e.g I test this with vector [ 1 2 3 4 4 3 2 1], expecting i to give 5 - the value of the second maximum, but instead it is returning y and I am not sure why??
Many thanks !
Answers (1)
Image Analyst
on 21 Nov 2020
True. That's just the way max() works. It only returns the first index if the max exists at multiple indexes. To find all the indexes where the max occurs you need to use find():
maxValue = max(x)
indexes = find(x == maxValue)
1 Comment
Sara Ismail-Sutton
on 22 Nov 2020
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!