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.

 Accepted Answer

James Tursa
James Tursa on 5 Feb 2021
Edited: James Tursa on 5 Feb 2021
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 Comments

This ended Up working but only after i replaced BOTH dydt(1) and dydt(2) with g(t) and f(t)
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)]

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Products

Release

R2020b

Community Treasure Hunt

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

Start Hunting!