Help to find errors of if loop?
1 view (last 30 days)
Show older comments
Example Complex: for,if... loop;
clear;clc;
A=[400; 900; 200; 300; 100];
k=[4;1]; % index matrix
c=[11];
e=zeros(0);
for j=0:(length(k)-1);
b(j+1,:) = A(k(j+1,:), :); % call vector from index
if b(j+1,:)>200
c=union(c,b(j+1,:));
elseif (b(j+1,:)+100)>400
e=union(e,b(j+1,:));
end
end
I try to run the simpe above code to understand: if elseif loop.
Explanation of code (for ...end):
-j=0-->k(1,:)=4-->b(4,:)=A(4,:)=300 [get value from matrix A at index 4]
-j=1-->k(2,:)=1-->b(1,:)=A(1,:)=400 [get value from matrix A at index 1]
Finally we will have result matrix b=[300;400]----> GOOD
But for the (if ....elseif ...end), i hope that the result matrix e=[400], but when I run the code matrix e=[] ?????????? Can you help me where the error?
My understanding of all loops:
-j=0-->k(1,:)=4-->b(4,:)=A(4,:)=300
if b(4,:)=300>200 ---> c=[11 300]
elseif b(4,:)=300+100=400>400 : NO--->e=[]
-j=1-->k(2,:)=1-->b(1,:)=A(1,:)=400
if b(1,:)=400>200 ---> c=[11 300 400]
elseif b(1,:)=400+100=500>400: YES --->e=[400]
Finally: e=[400] : as my understanding? (How can i fix the code to get the result as my understanding)
4 Comments
Guillaume
on 30 Aug 2017
Edited: Guillaume
on 30 Aug 2017
@Adam, the j=0 is not a problem as all indexing is done with j+1. Of course, rather than going from 0 to numel(k)-1 and then adding one to all the values for indexing, it would be a lot simpler to just go from 1 to numel(k) and not add anything:
for j = 1:numel(k)
b(j) = A(k(j, :), :);
is a lot simpler.
Accepted Answer
Jan
on 30 Aug 2017
Edited: Jan
on 30 Aug 2017
Do you know the debugger? You can set a break point in the first line and step through the code line by line. This will reveal directly, what happens inside the code.
In the second iteration b is the vector [300; 400]. Then:
if b(j+1,:) > 200
has a vector as condition. Note that if requires a scalar as argument, and therefore Matlab inserts this internally:
cond = (b(j+1,:) > 200);
if (all(cond(:)) && ~isempty(cond)
Here both elements of b are greater than 200, such that the code might do what you expect - by accident.
But the main problem remains, that you seem to assume, that the elseif branch is executed even if the if branch was already. But this is not the meaning of elseif.
I cannot guess, how you want to treat the problem of the vector input for the condition. But maybe it is enough already to replace if ... elseif ... end by if ... end, if ... end.
Note: The intention of the code is not clear. I guess boldly, that it can be simplified massively, perhaps by:
Ak = A(k);
c = unique([11; Ak(Ak > 200)]);
e = unique(Ak(Ak > 300));
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!