Borrar filtros
Borrar filtros

second maximum- not returning index

3 visualizaciones (últimos 30 días)
Sara Ismail-Sutton
Sara Ismail-Sutton el 21 de Nov. de 2020
Comentada: Sara Ismail-Sutton el 22 de Nov. de 2020
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 !

Respuestas (1)

Image Analyst
Image Analyst el 21 de Nov. de 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 comentario
Sara Ismail-Sutton
Sara Ismail-Sutton el 22 de Nov. de 2020
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

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by