How do I plot this piecewise function?
Ältere Kommentare anzeigen
I am trying to plot a piecewsie function. I followed the instructions on the following page:
However, I keep getting this error message:
Error using fplot
Input must be a function handle or symbolic function.
Error in piecwise (line 9)
fplot(x)
This is my code:
clear all;
clc;
grid on;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
syms t
x = piecwise(t <= -2, 0, -2 <= t <= 0, ((2 + t) / 2)^2, 0 <= t <= 2, 1, 2 <= t <= 4, ((4 - t) / 2)^2, t >= 4);
fplot(x)
This is the piecewise function I am trying to plot:

Any help is greatly appreciate!
Akzeptierte Antwort
Weitere Antworten (2)
First, I think it's "piecewise" instead of "piecwise"
Second, you should write "fplot(t,x)".
So, the code should be
syms t
x = piecewise(t <= -2, 0, -2 <= t <= 0, ((2 + t) / 2)^2, 0 <= t <= 2, 1, 2 <= t <= 4, ((4 - t) / 2)^2, t >= 4);
fplot(t,x)
2 Kommentare
Carter Sorensen
am 3 Jul. 2022
Good catch with the fplot(). I completely missed that...
dongshan xie
am 4 Jul. 2022
Thank you!
Carter Sorensen
am 3 Jul. 2022
Bearbeitet: Carter Sorensen
am 3 Jul. 2022
Hello,
Couldn't quite get fplot() to work with the piecewise() function. One workaround I found is to store the values you want to test in a matrix. Afterwards, pass each value in the matrix to the piecewise() function. From here, plot the outputs against the inputs using the plot() command. The described process may not be the most efficient, but it should work.
Sample code (inputs and outputs) has been included. Are you required to use fplot()?
Let me know if anything is unclear. Thanks!
clear all;
clc;
grid on;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
num = [-10:1:10]; % Sample numbers in matrix
syms x(t)
x(t) = piecewise(t <= -2, 0, -2 <= t <= 0, ((2 + t) / 2)^2, 0 <= t <= 2, 1, 2 <= t <= 4, ((4 - t) / 2)^2, t >= 4); % Your piecewise functions
results = x(num); % Plug numbers in matrix 'num' into x(t)
grid on
plot(num, results, 'linewidth', 3) % Plot all num values against corresponding x(t) values
xlabel('num')
ylabel('x(t)')
Kategorien
Mehr zu Assumptions finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


