Plotting Piecewise Functions in Matlab

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

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

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.