Why does Matlab execute both the elseif statement as well as the else statement?
7 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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
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.
Risposte (1)
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')
0 Commenti
Vedere anche
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!