How can I make this function\'s graph in Matlab, so that its body is depicted in the same graph (plot or subplot)?
t0=0.15
x(t)= 1, if 0<=t<(
The real question you should be asking is "How to define a function that has branches?", since plotting is easy once the function is defined.
Here's a way using anonymous functions:
x_t = @(t,t0)1*(0<=t & t<t0/2)-2*(t0/2<=t & t<=(3/2)*t0); %// the 1* is redundant, I only
%// left it there for clarity
Note that the & operator expects arrays and not scalars.
Here's a way using heaviside (aka step) functions (not exactly what you wanted, due to its behavior on the transition point, but worth mentioning):
x_t = @(t,t0)1*heaviside(t)+(-1-2)*heaviside(t-t0/2)+2*heaviside(t-t0*3/2);
Note that in this case, you need to "negate" the previous heaviside
once you leave its area of validity.
After defining this function, simply evaluate and plot.
t0 = 0.15;
tt = -0.1:0.01:0.5;
xx = x_t(tt,t0);
plot(tt,xx); %// Or scatter(), or any other plotting function
BTW, t0
does not have to be an input to x_t
- if it is defined before x_t
, the value of t0
that exists in the workspace at that time will be captured and used, but this also means that if t0 changes later, this will not affect x_t
.
I'm not sure of what you want, but would it be it?
clc
close all
clear
t0 = 0.15;
t = 0:0.01:0.15;
x = zeros(size(t));
x(0 <= t & t < (t0/2)) = 1;
x((t0/2) <= t & t <= (3/2)*t0) = -2;
figure, plot(t, x, 'rd')
which gives,
Everything depends on the final t
, for example if the end t
is 0.3, then you'll get,