%% Initial Guess of BVP Solution
% Create an initial guess of the solution to a BVP, solve the BVP with bvp4c, and then extend the solution to a new domain.
% Forming a good initial guess of the solution to a BVP problem is perhaps the most difficult part of solving the problem. BVP solutions are not necessarily unique, so the initial guess can be the deciding factor in which of many solutions the solver returns. The initial guess should satisfy the boundary conditions, and the behavior inbetween should reflect your general expectations about the problem (whether the solution oscillates, is a simple linear function, and so on...).
% Consider the differential equation
% {y^{\prime } }^{\prime } =-y.
% The equation is subject to the boundary conditions
% y\left(0\right)=y\left(\pi \right)=0.
% The function that encodes the equation as a first-order system is
% function dydx = bvpfun(x,y)
% dydx = [y(2)
%        -y(1)];
% end
% Similarly, the function that encodes the boundary conditions is
% function res = bcfun(ya,yb)
% res = [ya(1)
%        yb(1)];
% end
% You either can include the required functions as local functions at the end of a file (as done here), or you can save them as separate, named files in a directory on the MATLAB path.
%
%% Initial Guess with Function Handle
% You reasonably can expect the solution to the equation to be oscillatory, so sine and cosine functions are a good initial guess of the behavior of the solution and its derivative between the fixed boundary points.
% function y = guess(x)
% y = [sin(x)
%      cos(x)];
% end
% Create a solution structure using 10 equally spaced mesh points in the domain \left\lbrack 0,\pi \right\rbrack and the initial guess function.

xmesh = linspace(0,pi,10);
solinit = bvpinit(xmesh,@guess);

%
%% Solve BVP
% Call bvp4c with the ode function, boundary conditions, and solution guess. Plot the result.

sol = bvp4c(@bvpfun, @bcfun, solinit);
plot(sol.x,sol.y,'-o')

%
%% Local Functions
% Listed here are the local helper functions that the BVP solver bvp4c calls to calculate the solution. Alternatively, you can save these functions as their own files in a directory on the MATLAB path.

function dydx = bvpfun(x,y) % equation being solved
dydx = [y(2)
       -y(1)];
end
%-------------------------------------------
function res = bcfun(ya,yb) % boundary conditions
res = [ya(1)
       yb(1)];
end
%-------------------------------------------
function y = guess(x) % guess at solution behavior
y = [sin(x)
     cos(x)];
end
%-------------------------------------------

% Copyright 2018 The MathWorks, Inc.