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

7 visualizzazioni (ultimi 30 giorni)
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 Commenti
Rick van den Hadelkamp
Rick van den Hadelkamp il 13 Lug 2017
Thanks a lot! As in most cases it turned out to be something really small....
Elias Gule
Elias Gule il 13 Lug 2017
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.

Accedi per commentare.

Risposte (1)

Jan
Jan il 13 Lug 2017
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')

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by