MATLAB Answers

Ha Keat
0

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.

Asked by Ha Keat
on 16 May 2018 at 17:22
Latest activity Commented on by Rik Wisselink
on 18 May 2018 at 8:34
 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

  0 Comments

Sign in to comment.

2 Answers

Answer by Rik Wisselink
on 16 May 2018 at 18:00
Edited by Rik Wisselink
on 16 May 2018 at 18:22
 Accepted Answer

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

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.


Answer by the cyclist
on 16 May 2018 at 18:00

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.

  0 Comments

Sign in to comment.


Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today