フィルターのクリア

How do you sum concatenated variables in a system of ODES with a For Loop?

2 ビュー (過去 30 日間)
N = 3
% custom MATLAB function containing ODES
function dCdt = model(t,C,N)
% Inner Parameters
A = 3;
B = 2;
h = 10/N
% ODE system initialization
dCdt = zeros(N,1);
K1 = 0;
K2 = C(1)*A + B;
K3 = C(2)*A + B;
sumK = K2 + K3;
% ODES
dCdt(1) = 0;
dCdt(2) = -((C(2)-C(1))/h) + K2/sumK;
dCdt(3) = -((C(3)-C(2))/h) + K3/sumK;
end
Above you can see a static example of an ODE system with three ODEs. However, I want to automate this function so It can handle any number ("N") of ODEs. I have not found a way to include a For Loop inside the function that not only updates the number of ODEs but also the lengh of the "K" summation. Since the first ODE will always be equalt to zero, I can easialy run a for loop to define ODES from 2 to N. But, How would I write an expression that also update the concatenated summation term for any "N" value?
Thank you for your time and support!
  2 件のコメント
Jan
Jan 2022 年 3 月 18 日
Hint: The "k3" should be "K3" (upper case) I assume.
Roger Vegeta
Roger Vegeta 2022 年 3 月 18 日
Yes!

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

採用された回答

Davide Masiello
Davide Masiello 2022 年 3 月 18 日
編集済み: Davide Masiello 2022 年 3 月 18 日
This should do it for any N
N = 3;
[t,X] = ode45(@(t,C)model(t,C,N),[0,2],rand(1,N));
plot(t,X)
legend('c1','c2','c3')
function dCdt = model(t,C,N)
% Inner Parameters
A = 3;
B = 2;
h = 0.1; % <-- added a values for h
% ODE system initialization
dCdt = zeros(N,1);
K = zeros(N,1);
K(2:end) = C(1:end-1)*A + B;
sumK = sum(K(2:end));
dCdt(2:end) = -((C(2:end)-C(1:end-1))/h) + K(1)/sumK;
end
  6 件のコメント
Roger Vegeta
Roger Vegeta 2022 年 3 月 18 日
Awesome! Thank you so much this works!
Davide Masiello
Davide Masiello 2022 年 3 月 18 日
Anytime ;)

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

その他の回答 (1 件)

Jan
Jan 2022 年 3 月 18 日
編集済み: Jan 2022 年 3 月 18 日
This is trivial, if you do not create a bunch of variables, but an array:
K(1) = 0;
K(2) = C(1) * A + B;
K(3) = C(2) * A + B;
...
sumK = sum(K);
Or without a loop:
K = C * A + B;
If K1 is 0, the last term of the ODEs will vanish in all cases, so simply omit it.

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by