second maximum- not returning index

2 次查看(过去 30 天)
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 !

回答(1 个)

Image Analyst
Image Analyst 2020-11-21
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 个评论
Sara Ismail-Sutton
Sara Ismail-Sutton 2020-11-22
okay many thanks for your reply, I don't suppose you could help with my next issue.
The issue is with line 18 of the code below. I tested it with the vector C =[1 2 3 4 4 3 2 1], and used the de-bugging step, to view it step by step, and it skips past the if statement on line 18 " if ((find(M(i,:)==val(i)))==1) " whereas this should return a match with the value of 4 at index 4 to the value of 4 at indedx 5. I can not work out why it is skipping back this - i.e. returning a negative for the find value. Many thanks in advance :) (for more background the function is trying to find a saddle point, I'm aware it's probbaly not optimal etc but I think it's best if I learn that myself, and for now if someone could just address my question above. Many thanks ! )
function[indices]=checkingrow(M)
[ b1 b2] = size (M);
%for each row get vector of values
%and vector of indexes seperately
indices=[0,0];
for i=1:b1;
[val(i)]=max(M(i,:));
[~, c]=max(M(i,:));
[k,l]=min(M(:,c));
if l==i
indices=[i,c]
if ((find(M(i,:)==val(i)))==1)
[ind(i)] = find(M(i,:) == val(i))
[z,w]=min(M(:,ind(i)));
if ind(i)==w
indices2=[i,w]
end
end
else indices=indices;
end
end
if indices==[0,0]
indices=zeros(b1,b2)
end
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by