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.

 Respuesta aceptada

James Tursa
James Tursa el 5 de Feb. de 2021
Editada: James Tursa el 5 de Feb. de 2021

1 voto

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 comentarios

max french
max french el 5 de Feb. de 2021
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 el 5 de Feb. de 2021
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)]

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Programming en Centro de ayuda y File Exchange.

Productos

Versión

R2020b

Etiquetas

Preguntada:

el 5 de Feb. de 2021

Comentada:

el 5 de Feb. de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by