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

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

Try using the debugger (set some breakpoints) to go through your code line by line, this usually helps finding out where your program takes an unexpected turn. If you give those disp commands their own lines, you can even set the breakpoints there. The benefit is that you can find out what the workspace is at the point that the line is executed.
Thanks a lot! As in most cases it turned out to be something really small....
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개)

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')

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2017년 7월 13일

답변:

Jan
2017년 7월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by