Reputation: 157
I am trying to integrate a set of ordinary differential equations and calculate the solution and its first order derivative at given points. Matlab provides "ode45" to solve the equations and "deval" to calculate the solution and its first derivative, however, I am not able to use them in my case.
Matlab gives the following example:
sol = ode45(@vdp1,[0 20],[2 0]);
x = linspace(0,20,100);
y = deval(sol,x,1);
plot(x,y);
where I guess "vdp1" has been defined by Matlab and this example worked well. However, when I tried to use the following codes:
sol = ode45('vdp1',[0 20],[2 0]);
x = linspace(0,20,100);
y = deval(sol,x,1);
plot(x,y); it claims error:
"Error using deval (line 46) sol must be a structure returned by a differential equation solver."
So I think I have to use "@vdp1" in "ode45" instead of "'vdp1'", otherwise "deval" would not work.
But in my case I defined my derivative in a file as the following:
function dv = der( ~,vec,~,alpha, eta, m )
%UNTITLED4 Summary of this function goes here
% Detailed explanation goes here
vx=vec(1);
vy=vec(2);
vz=vec(3);
dv(1,1)=(alpha-eta*vx)/m;
dv(2,1)=(alpha-eta*vy)/m;
dv(3,1)=(alpha-eta*vz)/m;
end
I can use "ode45" to solve the equation with the following codes:
clear all;
% Parameters
alpha=10;
eta=0.5;
m=1;
% Inititial conditions
vec_ini=[0,0,0]';
% Integration time
Tf=10;
OPTIONS=odeset('abstol',1e-6,'reltol',1e-6);
sol=ode45('der',[0,Tf],vec_ini,OPTIONS,alpha,eta,m);
The codes worked. But when I added two more lines to use "deval" as follows
tvec=linspace(0,Tf,10);
[sxint,spxint]=deval(sol,tvec);
it saied:
Error using deval (line 46)
sol must be a structure returned by a differential equation solver.
If I change the ode45 part as
sol=ode45(@der,[0,Tf],vec_ini,OPTIONS,alpha,eta,m);
it said
Error using der (line 9)
Not enough input arguments.
Error in odearguments (line 88)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode45 (line 114)
[neq, tspan, ntspan, next, t0, tfinal, tdir, y0, f0, odeArgs, odeFcn, ...
So can anyone tell me how to use "ode45" and "deval" to calculate the solution and its first derivative with a customer defined derivative?
Upvotes: 1
Views: 2054
Reputation: 13876
I think you are not using the function handle correctly. I would suggest rewriting your der
function as follows:
function dv = der( t,y,params )
vx=y(1);
vy=y(2);
vz=y(3);
dv(1,1)=(params(1)-params(2)*vx)/params(3);
dv(2,1)=(params(1)-params(2)*vy)/params(3);
dv(3,1)=(params(1)-params(2)*vz)/params(3);
end
and then olving the ode
as follows:
params = [alpha eta m];
sol=ode45(@(t,y) der(t,y,params),[0,Tf],vec_ini,OPTIONS);
tvec=linspace(0,Tf,10);
[sxint,spxint]=deval(sol,tvec);
Upvotes: 2