Is there a way to use symbolic functions in ode45

조회 수: 16 (최근 30일)
Charles
Charles 2020년 11월 18일
댓글: Charles 2020년 11월 18일
Hey there, I'm trying to implement the following:
A matlab script that uses ode45 to solve a differential equation numerically and then plot it.
The catch is that i'd like to be able to use different user defined functions as "parameters" in my differential equation.
For example my differential equation is something like this: dxdt = (f'(t)-h'(t)) * x(t) where f(t) and h(t) are user defined functions.
I know that to use ode45 i have to define my diff equation as a function like:
function dydt = ode1(t,y)
dydt = -sin(y) + t + 1;
end
I also know that it's possible to define functions like this:
syms x
f(x) = sqrt(x) + 2
But when I can't use this solution since ode45 tells me that i can't use symbolic functions in my diff equation.
Is there any way to define a general diff equation or I will have to define a new equation function for each case?

채택된 답변

James Tursa
James Tursa 2020년 11월 18일
편집: James Tursa 2020년 11월 18일
Convert it to a function handle so that it can be used with numeric inputs. E.g.,
>> syms x
>> f(x) = sqrt(x) + 2
f(x) =
x^(1/2) + 2
>> F = matlabFunction(f)
F =
function_handle with value:
@(x)sqrt(x)+2.0
>> DF = matlabFunction(diff(f))
DF =
function_handle with value:
@(x)1.0./sqrt(x)./2.0

추가 답변 (1개)

Steven Lord
Steven Lord 2020년 11월 18일
You could make your function accept additional parameters. Then you could specify a function handle as that additional parameter.
% function that accepts parameters x (numbers) and fun (a function handle)
fh = @(x, fun) fun(x + 45);
format longg
% Work on sind()
S = @(x) fh(x, @sind);
sine135degrees = [S(90); sind(135)]
sine135degrees = 2×1
0.707106781186548 0.707106781186548
% Work on cosd()
C = @(x) fh(x, @cosd);
cosine135degrees = [C(90); cosd(135)]
cosine135degrees = 2×1
-0.707106781186548 -0.707106781186548
You could use S or C as your ODE function. Note that I didn't have to modify fh after I first defined it, S and C just use it along with their own specific "data" (@sind and @cosd).
  댓글 수: 1
Charles
Charles 2020년 11월 18일
This solution works as well, thank you so much.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by