Why does Matlab execute both the elseif statement as well as the else statement?
13 次查看(过去 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 个评论
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
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')
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!