MATLAB: ??? Undefined function or variable ‘x’

MATLAB

I am trying to use ode45 to solve a system of ODEs.
What I did was:
function Testfunction
tspan = [...]
%specify initial conditions
x0 = [...,...,...,...]
[t,x] = ode45(@somefn, tspan, x0)
%defining the output variables
y=x(:,1);
etc...
%plot stuff
plot(...)
return
%now define somefn
function g = somefn(t,x)
g = zeros(size(x));
g(1) = y;
etc...
return
But when I tried to run this code MATLAB keeps saying ??? Undefined function or variable 'x' in somefn
please could someone help me? Thanks.

Best Answer

Hi Richard, save your function
function g = somefn(t,x)
g = zeros(size(x));
g(1) = y;
end
in some folder on the MATLAB path and then call
[t,x] = ode45(@somefn,tspan,x0);
at the command line.
You are going to have a problem though, because somefn.m has to know what y is. It looks like you are using ode45 to return x and then using x to compute y, but you never pass y to the function somefn.m.
You have to give somefn.m everything it needs. Perhaps you can define that y internally inside the function?? Although you appear to have some recursive situation going on where you need the output of ode45() to feedback into ode45()...
Related Question