Why does Matlab execute both the elseif statement as well as the else statement?

조회 수: 8 (최근 30일)
Below i have put a part of my code. It uses a 7x2 matrix called Cable. XC and YC are starting coordinates which changes each loop.
When I execute it, the loop loops 6 times and it produces 6 rectangles (which is correct). However, it also executes the else part 'Does not fitt'. How is this possible? Thanks!
for i=1:6
if Cable{I}(i,1)<=X
if Cable{I}(i,2)<=Y
if Cable{I}(i,1)<=(X-XC(i,1))
A=rectangle('Position',[XC(i,1) YC(i,1) Cable{I}(i,1) Cable{I}(i,2)],'FaceColor','Blue');
XC(i+1,1)=XC(i,1)+Cable{I}(i,1);
YC(i+1,1)=YC(i,1)-(Cable{I}(i,2)-Cable{I}(i+1,2));
elseif Cable{I}(i,2)<=min(YC(:,1))
XC(i,1)=0;
YC(i,1)=min(YC(1:i-1,1))-Cable{I}(i,2);
A=rectangle('Position',[XC(i,1) YC(i,1) Cable{I}(i,1) Cable{I}(i,2)],'FaceColor','Blue');
XC(i+1,1)=XC(i,1)+Cable{I}(i,1);
YC(i+1,1)=YC(i,1)+(Cable{I}(i,2)-Cable{I}(i+1,2));
else disp('Does not fitt')
end
end
else disp('Does not fit')
end
end
  댓글 수: 3
Rick van den Hadelkamp
Rick van den Hadelkamp 2017년 7월 13일
Thanks a lot! As in most cases it turned out to be something really small....
Elias Gule
Elias Gule 2017년 7월 13일
if Cable{I}(i,1)<=X
if Cable{I}(i,2)<=Y
doSomething(); %%The inner if statement
else
disp('Does not fit')
end
end
It appears that there is an instance in your code where the condition
Cable{I}(i,2) <= Y
is not true. Hence the execution of else part.

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

답변 (1개)

Jan
Jan 2017년 7월 13일
Using the debugger by setting breakpoints in the two "disp('Does not fitt')" lines will reveal, what's going on. If Matlab stops in one of these lines, you can check the value of the correspodning IF condition.
Note that it might increase the level of clarity, if the two messages are different:
disp('Does not fit: inner loop')
...
disp('Does not fit: outer loop')

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by