You are using else if as if it was elseif
That is,
if condition1
action1
else if condition2
action2
end
is not valid. Valid would be
if condition1
action1
else if condition2
action2
end
end
which is equivalent to
if condition1
action1
else
if condition2
action2
end
end
Also legal is
if condition1
action1
elseif condition2
action2
end
Notice there is only a single end
You are probably wondering what the difference is between them. Well suppose you had
r = rand;
if r <= 1/2
disp('first half')
else if r <= 3/4
disp('third quarter')
end
disp('another message')
end
Then when we space it better, we get
r = rand;
if r <= 1/2
disp('first half')
else
if r <= 3/4
disp('third quarter')
end
disp('another message')
end
and you can see that 'another message' sent out as long as r <= 1/2 is false, including if r <= 3/4 is ture. But if we had
r = rand;
if r <= 1/2
disp('first half')
elseif r <= 3/4
disp('third quarter')
end
disp('another message')
then "another message" is always sent out.
Best Answer