I want to build a function that must switch between +1 and -1 and since it should be put in ode45 I can't use piecewise, thus I thought about using the heaviside function.
rf=3;
m=2;
b=2;
k=1;
d=2;
M=m+b;
g = M*d/(2*(m*b));
w = sqrt(k*M/(m*b));
A=[0 1 0 0;0 0 0 0;0 0 0 1;0 0 -w^2 -2*g];
B=[0;1/M;0;1/b];
t1=2*sqrt(M*rf/3);
t2=5*sqrt(M*rf/3);
tf=6*sqrt(M*rf/3);
t_interval=[0, tf];
x0=[rf;0;0;0];
u = @(t) control_input(t,t1,t2,tf);
[t,x]=ode45(@(t,x) A*x+B*u(t),t_interval,x0);
function u = control_input(t,t1,t2,tf)
if t<= t1
u=-heaviside(t); % Control input -1 before t1 switch
elseif t1<t<=t2
u= heaviside(t); % Control input +1 before t2 switch
elseif t2<t<=tf
u=-heaviside(t); % Control input -1 until tf
end
end
The problem is that I expect my input u to be -1 in [0,t1], +1 in (t1,t2], and -1 in (t2,tf], but plotting u I obtain:

Now, here comes the problem: I expected to be three 'pieces' of function instead of two. Where is the problem?
I tried to use
if t <= t1
u = -1; % Control input -1 before t1_switch
elseif t1<t<=t2
u = +1;% Control input +1 before t2_switch
elseif t2<t<=tf
u=-1;%up to tf
end
Now u(t) starts at -1, then jumps to +1 but does not jump back to -1.