if statement not working

조회 수: 1 (최근 30일)
Marisabel Gonzalez
Marisabel Gonzalez 2019년 4월 5일
댓글: Marisabel Gonzalez 2019년 4월 5일
Hi, my following piece of code does not work as it expected to and I don't know how to fix it yet. Any suggestions? Thanks!
A = [5;5;5;3;3;2];
B = [10;4;10;10;4;4];
if A == 5
plot(A,B,'rx')
elseif A == 3
hold on
plot(A,B,'bx')
else
hold on
plot(A,B,'gx')
end
  댓글 수: 2
Stephen23
Stephen23 2019년 4월 5일
"if statement not working"
Did you read the IF documentation (to know how it works with non-scalar conditions), before deciding that it is "not working" ?
Rik
Rik 2019년 4월 5일
편집: Rik 2019년 4월 5일
@Stephen I think Matlab should throw a warning on non-scalar inputs, maybe even an error. I've many people surprised by the implicit call to all that happens here.
%actually, if does this:
if ~isempty(expression) && all(expression)

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

채택된 답변

Rik
Rik 2019년 4월 5일
편집: Rik 2019년 4월 5일
What you probably think should happen is in the code below, however, there is a better way.
A = [5;5;5;3;3;2];
B = [10;4;10;10;4;4];
figure(1)
clf(1),axes;
for n=1:numel(A)
if A(n) == 5
plot(A(n),B(n),'rx')
elseif A(n) == 3
hold on
plot(A(n),B(n),'bx')
else
hold on
plot(A(n),B(n),'gx')
end
end
axis([1 6 3 11])
The better way is to use logical indexing:
A = [5;5;5;3;3;2];
B = [10;4;10;10;4;4];
figure(1),clf(1)
already_plotted=false(size(A));
L= A == 5;
plot(A(L),B(L),'rx')
already_plotted(L)=true;
hold on
L= A == 3 & ~already_plotted;
plot(A(L),B(L),'bx')
already_plotted(L)=true;
L= ~already_plotted;
plot(A(L),B(L),'gx')
axis([1 6 3 11])
axis([1 6 3 11])
  댓글 수: 3
Rik
Rik 2019년 4월 5일
See my edited answer. You will only see 5 points, because two of them overlap (5,10).
Marisabel Gonzalez
Marisabel Gonzalez 2019년 4월 5일
Makes sense. Thank you once again!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Graphics Performance에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by