## Why Matlab only run the "else" function equation even "a" fulfils the condition in "if" function? The graph is plotted based on the equation in "else" function only no matter whether "a" is less than 198 or not.

### Ha Keat (view profile)

on 16 May 2018
Latest activity Commented on by Rik Wisselink

on 18 May 2018

EL=15;
for X=3:3:EL;
dx=600/X;
a=0:dx:600;
if a<198
y=113+113*(cos(pi*a/200));
else
y=(exp(-a/100)).*(((113)*(cos(pi*a/200)))+(113));
end
figure(4)
plot(a,y,'-ob')
title('ABC','fontsize',15)
xlabel('x-coordinate');
ylabel('y-coordinate');
end

### Tags

on 16 May 2018

on 16 May 2018

If you are on R2018a you will see an m-lint warning that a is a non-scalar operator (and maybe earlier show it as well). The if statement uses an implicit call to all if you put a logical array as a parameter. Pre-allocate and use indexing. Also, you are overwriting all your data each and every loop.
EL=15;
figure(4),clf(4)
for X=3:3:EL
dx=600/X;
a=0:dx:600;
y=zeros(size(a));
a_=a( a<198 );
y ( a<198 )=113+113*(cos(pi*a_/200));
a_=a(~(a<198));
y (~(a<198))=(exp(-a_/100)).*(((113)*(cos(pi*a_/200)))+(113));
plot(a,y,'-ob'),hold on
end
title('ABC','fontsize',15)
xlabel('x-coordinate');
ylabel('y-coordinate');

#### 1 Comment

on 18 May 2018
Did this suggestion solve your problem? If so, please consider marking it as accepted answer. If this didn't solve your question, please comment with what problems you are still having.