MATLAB: solving a 2nd order ODE which has a parameter which evolves in time

Hi, I'm trying to solve the equation: y'' + k(t)y = 0 where k(t) is an array of values and y(0) = 1/2 and y'(0) = 1 in the range t = 0 to 20.
I understand it is possible to solve this as 2 coupled first order differential equations using ode45 as follows when k is constant:
k = 2
syms y(t)
[System] = odeToVectorField(diff(y, 2) == -(k).*y);
M = matlabFunction(System,'vars', {'t','Y'});
sol = ode45(M,[0 20],[1/2 1]);
fplot(@(x)deval(sol,x,1), [0, 20])
Please will you help me introduce the dependance on t of k(t), thanks!

1 件のコメント

darova
darova 2020 年 2 月 24 日
  • Please will you help me introduce the dependance on t of k(t), thanks!
Can you be more specific? What is it? Where is dependance?

サインインしてコメントする。

 採用された回答

Star Strider
Star Strider 2020 年 2 月 24 日
Try this:
syms k(t) y(t) % Declare ‘k(t)’ Here
[System,Subs] = odeToVectorField(diff(y, 2) == -(k).*y); % Note ‘k(t)’ Included In Code
M = matlabFunction(System,'vars', {'t','Y'})
kv = rand(1,20); % ‘k’ Vector
tv = linspace(0, 20, numel(kv)); % Time Vector Matching ‘k’
k = @(t) interp1(tv, kv, t, 'linear', 'extrap'); % Function Interpolating ‘k’ To Specific Time
M = @(t,Y)[Y(2);-k(t).*Y(1)]; % Output Of 'matlabFunction’ (Needs To Be Copied, And Pasted In The Code After The 'k' Function Is Defined)
[T,Y] = ode45(M,[0 20],[1/2 1]);
figure
plot(T, Y)
grid
xlabel('T')
ylabel('Amplitude')
legend(string(Subs))
Use your own ‘kv’ vector. The rest of the code should adapt to it, whatever it is.

6 件のコメント

Mark Anslow
Mark Anslow 2020 年 2 月 24 日
Thank you!
Star Strider
Star Strider 2020 年 2 月 24 日
As always, my pleasure!
J. Alex Lee
J. Alex Lee 2020 年 2 月 24 日
As long as you are allowed to make k a function handle, can you simply encode the equation that generates kv and tv?
k = @(t)(exp(t))
For example, would be better than
tv = linspace(0,10,100);
kv = exp(tv);
k = @(t) interp1(tv, kv, t, 'linear', 'extrap'); % Function Interpolating ‘k’ To Specific Time
Or is there something about symbolic toolbox that it won't work this way?
Star Strider
Star Strider 2020 年 2 月 24 日
@J. Alex Lee —
... where k(t) is an array of values ...
So your idea is not appropriate here.
J. Alex Lee
J. Alex Lee 2020 年 2 月 24 日
oops guess i need help with reading skills. i saw a similar question before, where "k(t)" in the function sense was being confused with "k(t)" in the index sense. Hope this isn't one of those cases and one really needs the discretized time-dependence.
Star Strider
Star Strider 2020 年 2 月 24 日
Noted.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

製品

リリース

R2017b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by