Solve ODE with array forcing function

24 ビュー (過去 30 日間)
MR
MR 2024 年 11 月 19 日 16:51
編集済み: Torsten 2024 年 11 月 19 日 20:02
I want to solve a simple ODE of the form like below ( current in a RL circuit):
dIdt= k1*I+k2*V, where k1 and k2 are constants.
V is a vector of recorded voltage data that can be thought of as V(t) at a specified sampling frequency fs. All examples I find have the forcing term with a dependency on t like sin(t).
How can I formulate this so that my forcing function V gets used without an explicit dependency on t?
Something like:
[t,I]=ode45( @rhs, t, initial_I, k1,k2 V);
function dIdt=rhs(t,x)
dIdt = k1*I + k2*V;
end

採用された回答

Swastik Sarkar
Swastik Sarkar 2024 年 11 月 19 日 17:46
Hi @MR,
The ode45 function is typically used with continuous functions. When working with custom discrete functions, interpolation is necessary so that the solver can handle the data. Here is an example demonstrating this approach:
k1 = -0.5;
k2 = 1.0;
V = [0, 1, 0.5, -0.5, -1, 0, 0.8, 0.2, -0.2, -0.8, 0];
T = numel(V) - 1;
t_V = 0:T;
V_interp = @(t) interp1(t_V, V, t, 'linear', 'extrap');
rhs = @(t, I) k1 * I + k2 * V_interp(t);
t_span = [0, T]; % Going beyond this value may bring in undesired results
[t, I] = ode45(rhs, t_span, 0);
figure;
plot(t, I, 'b-', 'LineWidth', 2);
xlabel('Time (s)');
ylabel('Current (I)');
title('Current in RL Circuit');
grid on;
figure;
stairs(t_V, V, 'r-', 'LineWidth', 1.5);
xlabel('Time (s)');
ylabel('Voltage (V)');
title('Voltage Input');
grid on
To learn more about ode45, please refer to the following documentation:
Hope this is helpful.
  2 件のコメント
MR
MR 2024 年 11 月 19 日 18:34
Well then is there a built-in way to ''numerically'' solve these type of equations? By this I mean keeping everything discrete, no interpolation? I don't ''absolutely'' want to use ODE45.
Thanks.
Torsten
Torsten 2024 年 11 月 19 日 19:55
編集済み: Torsten 2024 年 11 月 19 日 20:02
Well then is there a built-in way to ''numerically'' solve these type of equations?
This is the way to solve "these type of equations".
Look at the example
"ODE with Time-Dependent Terms"
under
If you want to keep everything discrete, you will have to code "Euler forward" with the step size dt chosen as the difference between subsequent times at which V(t) is recorded.
V = ...;
T = ...;
I(1) = I0;
for i = 1:numel(T)-1
I(i+1) = I(i) + (T(i+1)-T(i))*(k1*I(i)+k2*V(i));
end

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCircuits and Systems についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by