Need help with solving a problem
Show older comments
I don't understand what I am doing wrong and why it's not working.
x = 0:pi/12:2*pi;
if x >= 0 && x < pi/2
y = 6*(2*x-.5*sinx)/pi;
elseif x >= pi/2 && x < 2*pi/3
y = 6;
elseif x >= 2*pi/3 && x > 4*pi/3
y = 6 - 3*(1-.5*cos(3*(x-2*pi/3)));
elseif x >= 4*pi/3 && x < 3*pi/2
y = 3;
elseif x >= 3*pi/2 && x < 7*pi/4
y = 3 - 1.5*((x-3*(pi/2))/(pi/4))^2;
else x >= 7*pi/4 && x <= 2*pi;
y = 0.75 - 0.75*(1-(x-7*(pi/4))/(pi/4));
end
plot(x,y)
end
1 Comment
Adam
on 15 Mar 2016
You should have M-Lint messages with orange underlinings giving you assistance on what is wrong.
As soon as I paste your code into my editor it lights up with numerous of these.
Mostly the fact that x is a vector so statements like
if x >= 0 && x < pi/2
are unlikely to be doing what you want (and in this case using && instead of & is just a syntax error anyway).
You can do what you are aiming for using logical indexing rather than a bunch of if else statements
Answers (1)
x = 0:pi/12:2*pi;
y = zeros( size( x ) );
case1 = x >= 0 & x < pi/2;
y( case1 ) = 6*(2 * x( case1 )-.5*sin( x( case1 ) ))/pi;
case2 = x >= pi/2 & x < 2*pi/3;
y( case2 ) = 6;
case3 = x >= 2*pi/3 & x > 4*pi/3;
y( case3 ) = 6 - 3*( 1 - 0.5*cos( 3 * ( x ( case3 ) - 2*pi/3 ) ) );
case4 = x >= 4*pi/3 & x < 3*pi/2;
y( case4 ) = 3;
case5 = x >= 3*pi/2 & x < 7*pi/4;
y( case5 ) = 3 - 1.5*( ( x( case5 ) - 3*(pi/2)) / (pi/4)).^2;
case6 = x >= 7*pi/4 & x <= 2*pi;
y( case6 ) = 0.75 - 0.75*(1-( x( case6 ) - 7*(pi/4))/(pi/4));
figure; plot(x,y)
Something like the above should work. There were numerous syntax errors in your initial code, but the biggest being the use of && instead of & for vector operations and trying to put these into an if statement and expect it to work for all cases matching the logical expression.
My solution above is probably not the neatest, but it was a quick fix. Creating 6 named variables for the individual cases is not something I would recommend, but it gets the job done to show what needs doing.
If I had more time I would rationalise it into a neater way of describing the curve.
I haven't checked things like whether your 6 cases are all independent and covering the full range of x which is expected for this to work sensibly (you will get 0's in this solution anywhere where none of your cases match).
Categories
Find more on Entering Commands 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!