Input argument for ode45 function type error

I am trying to modify the following code.
tspan = [0 10];
x0 = 0;
[t,x] = ode45(@(t,x) (-4.76e+1*x^2 + 5.69e-9*x + 7.98e-2)/(1.67e+4*x + 1.12), tspan, x0);
plot(t,x,'b')
xlim([0 0.001])
The input argument to the ode45 function is directly typed in. If instead you write it as
tspan = [0 10];
x0 = 0;
f = (-4.76e+1*x^2 + 5.69e-9*x + 7.98e-2)/(1.67e+4*x + 1.12);
[t,x] = ode45(@(t,x) f, tspan, x0);
plot(t,x,'b')
xlim([0 0.001])
then there is an error, even though the type of the argument is the same. Can anyone explain how the argument can be input as a variable that stores the expression?

 Accepted Answer

Yes.
Create it as an anonymous function at the outset —
tspan = [0 10];
x0 = 0;
f = @(t,x) (-4.76e+1*x^2 + 5.69e-9*x + 7.98e-2)/(1.67e+4*x + 1.12);
[t,x] = ode45(f, tspan, x0);
figure
plot(t,x,'b')
grid
xlim([0 0.001])
.

4 Comments

Thank you for your help. The problem I was encountering is that I wanted to plot a symbolic expression using ode45 and the argument must be a function handle, so I converted the symbolic expression using matlabFunction but although it was converted to a function handle I still got an error.
syms x
f = (- 4.76e+67*x^2 + 5.69e+57*x + 7.98e+64)/(1.67e+70*x + 1.12e+66)
f = matlabFunction(f)
tspan = [0 10];
x0 = 0;
[t,x] = ode45(f, tspan, x0);
plot(t,x,'b')
grid
xlim([0 0.001])
How do you convert a symbolic expression like f to the appropriate type to be plotted using ode45?
As always, my pleasure!
It is necessary to include the 'Vars' optional argument to matlabFucntion to get the correct result —
syms x t
f = (- 4.76e+67*x^2 + 5.69e+57*x + 7.98e+64)/(1.67e+70*x + 1.12e+66)
f = 
f = matlabFunction(f, 'Vars',{t,x})
f = function_handle with value:
@(t,x)(x.*5.69e+57-x.^2.*4.76e+67+7.98e+64)./(x.*1.67e+70+1.12e+66)
tspan = [0 10];
x0 = 0;
[t,x] = ode45(f, tspan, x0);
plot(t,x,'b')
grid
xlim([0 0.001])
Using 'Vars' so that the created function is of both ‘t’ and ‘x’ (and in the specified order of the ‘Vars’ matching value) creates a function that ode45 and the others can use.
Note — This also requries adding ‘t’ to the syms declaration.
.
Thank you, I appreciate your help
As always, my pleasure!
.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!