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)
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 Exchange에서 Programming에 대해 자세히 알아보기

제품

릴리스

R2020b

태그

질문:

2021년 2월 5일

댓글:

2021년 2월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by