finding value of matrix in an if statement

조회 수: 30 (최근 30일)
Sara Ismail-Sutton
Sara Ismail-Sutton 2020년 11월 24일
편집: Jon 2020년 11월 24일
e 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
  댓글 수: 1
Jan
Jan 2020년 11월 24일
편집: Jan 2020년 11월 24일
You forgot to mention, what the code should do. The readers cannot guess this detail.
Omit the useless code indices=indices;
Combine the code:
[val(i)]=max(M(i,:));
[~, c]=max(M(i,:));
to
[val(i), c] = max(M(i,:));

댓글을 달려면 로그인하십시오.

답변 (1개)

Jon
Jon 2020년 11월 24일
편집: Jon 2020년 11월 24일
I'm not sure exactly what you are trying to do, but I will try to explain what your statement is doing and why it might not be what you intended, here is your statement
((find(M(i,:)==val(i)))==1)
just to be concrete, suppose for example M(i,:) = [1 8 4 2 7 4] and val(i) = 4 then
M(i,:)==val(i)
will give a logical vector [false false true false false true]
performing a find on this will return the indices where the logical vector is true, so
find(M(i,:)==val(i))
will return the vector [3,6]
finally
find(M(i,:)==val(i)))==1
will return a logical vector whose elements are true where the vector [3,6] is equal to 1, so
[false false], since neither 3 or 6 equals 1
Your statement will only evaluate to true if the first element of M(i,:) equals val(i)
By the way, if you select all of your code and then right click and select smart indent your code will be much more readable.

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by