Ok, so i have a ODE that i KNOW works if i type it manually but it can change based on earlier calculations.So i had it put the equation as a string, and inputed into a ODEfunc command.
Example at moment,
function dydt = ODEfunc512(A,W,t,str)
dydt = zeros(2,1);
dydt(1) = A*cos(W*t);
dydt(2) = str;
%exp(-t/2)*(C1*cos((3^(1/2)*t)/2) - C2*sin((3^(1/2)*t)/2));
end
(The % is the equation in the str variable),
This works if i swap str with the comment, But not as it is, is there Any way of doing this? or is it a case of manually changing the code every time.

 採用された回答

James Tursa
James Tursa 2021 年 2 月 5 日
編集済み: James Tursa 2021 年 2 月 5 日

1 投票

What you might want to do is pass a function handle for this. E.g., in your calling code create the function handle:
C1 = whatever
C2 = whatever
f = @(t) exp(-t/2)*(C1*cos((3^(1/2)*t)/2) - C2*sin((3^(1/2)*t)/2))
If you are starting with a string in your calling code, you can create the function handle this way:
C1 = whatever
C2 = whatever
str = whatever
f = eval(['@(t)' str]); % use eval( ) instead of str2func( ) here so C1 and C2 get used
Then change your derivative function to take that as an argument and evaluate it inside the function. E.g.,
function dydt = ODEfunc512(A,W,t,f)
dydt = zeros(2,1);
dydt(1) = A*cos(W*t);
dydt(2) = f(t);
end
Using this design you can change the function at the caller level without having to change your derivative function each time you change the function.

2 件のコメント

max french
max french 2021 年 2 月 5 日
This ended Up working but only after i replaced BOTH dydt(1) and dydt(2) with g(t) and f(t)
James Tursa
James Tursa 2021 年 2 月 5 日
If you needed to replace both of them, then you may as well just use a function handle for this. E.g.,
ODEfunc512 = @(t)[g(t);f(t)]

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeProgramming についてさらに検索

製品

リリース

R2020b

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by