Is there a way to use symbolic functions in ode45

75 views (last 30 days)
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?

Accepted Answer

James Tursa
James Tursa on 18 Nov 2020
Edited: James Tursa on 18 Nov 2020
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

More Answers (1)

Steven Lord
Steven Lord on 18 Nov 2020
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).

Categories

Find more on Symbolic Math Toolbox in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!