ERROR USING A FUNCTION INSIDE ODE FUNCTION

조회 수: 1 (최근 30일)
Sam
Sam 2017년 12월 27일
댓글: Walter Roberson 2017년 12월 28일
I am trying to solve a 2nd order differential equation which involves invoking a function defined in the main code from inside another function. However, I am ending up with an error that says
Undefined function or variable 'partial_psi_x'.
Error in P3>odefunc (line 103)
dudt = -partial_psi_x(x,y,z);
Error in odearguments (line 90)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);
Error in P3 (line 91)
[t,s] = ode45(@odefunc, tspan, s0);
Relevant piece of code is as follows:
partial_psi_x = partial_psi_b_x + partial_psi_d_x + partial_psi_h_x;
partial_psi_y = partial_psi_b_y + partial_psi_d_y + partial_psi_h_y;
partial_psi_z = partial_psi_b_z + partial_psi_d_z + partial_psi_h_z;
partial_psi_x = matlabFunction(partial_psi_x);
partial_psi_y = matlabFunction(partial_psi_y);
partial_psi_z = matlabFunction(partial_psi_z);
% ODE
tstart = 0;
tstop = 2*pi;
tspan=tstart:tstop;
s0=[-R0;0;0;0;V0;0];
[t,s] = ode45(@odefunc, tspan, s0);
function dsdt = odefunc(t,s)
x = s(1);
y = s(2);
z = s(3);
u = s(4);
v = s(5);
w = s(6);
dxdt = u;
dydt = v;
dzdt = w;
dudt = -partial_psi_x(x,y,z);
dvdt = -partial_psi_y(x,y,z);
dwdt = -partial_psi_z(x,y,z);
dsdt = [dxdt;dydt;dzdt;dudt;dvdt;dwdt];
end
where partial_psi_x, partial_psi_y and partial_psi_z are function handles (after using MatlabFunction) to partial derivatives of a function psi in terms of x, y and z. I have checked until the point of obtaining the three function handles and they seem to work without any issues. However, when I try to access these functions from inside odefunc, I get error as mentioned above. I am fairly new to numerical integration technique in MATLAB but have tried to look up a similar approach of using functions inside an ode solver but could not find any solution. Any help on the issue will be highly appreciated.

채택된 답변

Walter Roberson
Walter Roberson 2017년 12월 27일
You should pass in those function handles as extra parameters.
  댓글 수: 4
Sam
Sam 2017년 12월 28일
Thanks! this works, but may I ask why the function handles haven't been included in the argument list after @?
Walter Roberson
Walter Roberson 2017년 12월 28일
They were included. ode45 is being passed multiple arguments, the first of which is
@(t,s) odefunc(t, s, partial_psi_x, partial_psi_y, partial_psi_z)
This constructs an anonymous function that takes two arguments. The action of the anonymous function is to call odefunc with 5 arguments.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by