Is there a way to use symbolic functions in ode45

14 次查看(过去 30 天)
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).

类别

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