MATLAB Answers

Help to find errors of if loop?

7 views (last 30 days)
ha ha
ha ha on 30 Aug 2017
Commented: ha ha on 30 Aug 2017
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
ha ha
ha ha on 30 Aug 2017
@Guillaume. good friend. You understand well.
@Adam: --> mean: refer (or we have)

Sign in to comment.

Accepted Answer

Jan
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));
  1 Comment
ha ha
ha ha on 30 Aug 2017
you are correct. just replace "if ... elseif ... end" by "if ... end, if ... end." . I will get the expected answer

Sign in to comment.

More Answers (0)

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!