MATLAB: ODE45, ODEfunc question

MATLABode45odefunc

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.

Best Answer

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.