# How to solve system of differential equations with time dependent parameters?

62 views (last 30 days)
Milena Capiglioni on 3 Apr 2020
Commented: Star Strider on 3 Apr 2020
Hello, I'm quite new to MATLAB and I'm having a problem when trying to solve the next system of differential equations for the case when Dw and w1 vary with time. For the case when w1 and Dw are constants the code works just fine with dsolve.
If I add the time dependent functions w1 and dw my code looks like:
%define constants
T1 = 0.6;
T2 = 0.1;
gamma = 4258;
dt = 0.0001;
Tp = 0.008;
Ns = Tp/dt;
B1 = 20;
f = 1200;
mu=6;
%define time dependent functions
syms t
w1 = @(t) B1*sech((pi*f/mu)*(t-Tp));
dw = @(t) pi*f*tanh((pi*f/mu)*(t-Tp));
syms x(t) y(t) z(t)
eqns = [diff(x(t),t) == -x(t)/T2 + dw(t)*y(t), diff(y(t),t) == -dw(t)*x(t) - y(t)/T2 + w1(t)*z(t),diff(z(t),t) == -w1(t)*y(t) - (z(t)-1)/T1];
cond = [x(0) == 0, y(0) == 0, z(0) == 1];
[xSol(t),ySol(t),zSol(t)] = dsolve(eqns,cond);
And I get the error:
Warning: Unable to find explicit solution.
> In dsolve (line 201)
Error using sym/subsindex (line 825)
Invalid indexing or function definition. Indexing must follow MATLAB indexing. Function arguments must be symbolic variables, and function body must be sym expression.
I also tried with ODE45 but I get a similar error. Apparently I am not using the correct syntax. I read all the mathlab helps I could find but I didn't find an answer useful for this case.

#### 1 Comment

darova on 3 Apr 2020
Can you show your attempt with ode45?

Star Strider on 3 Apr 2020
As darova suggested, integrate it numerically. For some reason, ode45 does not like the anonymous functions and throws an ’Undefined function or variable’ error (although I¹ve used them successfully in other situations to create time-varying parameters in numerically-integrated differential equations), so it’s necessary to include them in the actual code:
T1 = 0.6;
T2 = 0.1;
gamma = 4258;
dt = 0.0001;
Tp = 0.008;
Ns = Tp/dt;
B1 = 20;
f = 1200;
mu=6;
syms x(t) y(t) z(t) dw(t) w1(t) t Y
dw(t) = pi*f*tanh((pi*f/mu)*(t-Tp));
w1(t) = 1*sech((pi*f/mu)*(t-Tp));
eqns = [diff(x(t),t) == -x(t)/T2 + dw(t)*y(t), diff(y(t),t) == -dw(t)*x(t) - y(t)/T2 + w1(t)*z(t),diff(z(t),t) == -w1(t)*y(t) - (z(t)-1)/T1];
[VF,Subs] = odeToVectorField(eqns)
odefcn = matlabFunction(VF, 'Vars',{t,Y})
tspan = [0 1];
ic = [0 0 1];
[T,XYZ] = ode45(@(t,Y)odefcn(t,Y), tspan, ic);
figure
for k = 1:size(XYZ,2)
subplot(size(XYZ,2),1,k)
plot(T,XYZ(:,k))
grid
title(string(Subs(k)))
end
This ran without error in R2020a.