Plotting Piecewise functions in Matlab

$\begingroup$

I tried this code in MATLAB in order to plot the piecewise function:

f(x) = cos (x) for x < 0 and e^-x (1 - x^2) for x >= 0: p y=piecewise(x)

plot(x,y)

xlabel('x')

ylabel('y')

title('Plots of $y = \cos x$ and $e^(-x)(1 - x^2)$', 'interpreter', 'latex')

I can't seem to find much information online in regards to plotting these quite simplistic Piecewise functions in MATLAB.

$\endgroup$ 1

1 Answer

$\begingroup$

Install the symbolic math toolbox and then this should work:

syms x
y = piecewise(cos(x), x<0, exp(-x)*(1-x^2), x>=0)
fplot(y)
$\endgroup$

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like