MATLAB: Undefined function ‘f’

unrecognized function

tmesh = linspace(0,pi/2,5);
solinit = bvpinit(tmesh, @f);
sol = bvp4c(@odefun, @bcfun, solinit);
plot(sol.x, sol.y, '-o');
FUNCTION
function dzdt = odefun(t,z)
dzdt = zeros(2,1);
dzdt = [z(2)+z(1)];
end
% boundary conditions
function res = bcfun(za, zb)
res = [za(1) zb(pi/2)-2]
end
% Initial guess
function g = f(t)
g = [sin(t) cos(t)];
end
error unrecognized function or variable 'f'

Best Answer

Either write all the functions in one file like this. (Also note that I have made few changes in your code.)
tmesh = linspace(0,pi/2,5);
solinit = bvpinit(tmesh, @f);
sol = bvp4c(@odefun, @bcfun, solinit);
plot(sol.x, sol.y, '-o');
function dzdt = odefun(t,z)
dzdt = zeros(2,1);
dzdt = [z(2); z(1)]; % <----- This should be a 2x1 vector
end
% boundary conditions

function res = bcfun(za, zb)
res = [za(1); zb(2)-2]; % <---- boundary conditions are written like this, zb(pi/2) is invalid
end
% Initial guess

function g = f(t)
g = [sin(t) cos(t)];
end
Or create 4 files like this.
main_script:
tmesh = linspace(0,pi/2,5);
solinit = bvpinit(tmesh, @f);
sol = bvp4c(@odefun, @bcfun, solinit);
plot(sol.x, sol.y, '-o');
odefun.m:
function dzdt = odefun(t,z)
dzdt = zeros(2,1);
dzdt = [z(2); z(1)];
end
bcfun.m:
% boundary conditions
function res = bcfun(za, zb)
res = [za(1); zb(2)-2];
end
f.m:
% Initial guess
function g = f(t)
g = [sin(t) cos(t)];
end