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.

1 view (last 30 days)
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

Accepted Answer

Rik
Rik on 16 May 2018
Edited: Rik 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
Rik
Rik 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.

Sign in to comment.

More Answers (1)

the cyclist
the cyclist on 16 May 2018
The reason is that when you check a vector of condition, such as
a=[0 200 400 600];
if a<198
then all of the elements of a must be less than 198, in order to enter the if portion of the control structure.

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!