%% Solve Second-Order BVP
% Solve a second-order BVP in MATLAB® using functions. For this example, use the second-order equation
% {y^{\prime } }^{\prime } +y=0.
% The equation is defined on the interval \left\lbrack 0,\pi /2\right\rbrack subject to the boundary conditions
% y\left(0\right)=0,
% y\left(\pi /2\right)=2.
% To solve this equation in MATLAB, you need to write a function that represents the equation as a system of first-order equations, a function for the boundary conditions, and a function for the initial guess. Then the BVP solver uses these three inputs to solve the equation.
%
%% Code Equation
% Write a function that codes the equation. Use the substitutions y_1 =y and y_2 =y^{\prime } to rewrite the equation as a system of first-order equations.
% {y_1 }^{\prime } =y_2,
% {y_2 }^{\prime } =-y_1.
% The corresponding function is
% function dydx = bvpfcn(x,y)
% dydx = zeros(2,1);
% dydx = [y(2)
%        -y(1)];
% end
% Note: All functions are included at the end of the example as local functions.
%% Code Boundary Conditions
% Write a function that codes the boundary conditions in the form g\left(y\left(a\right),y\left(b\right)\right)=0. In this form the boundary conditions are
% y\left(0\right)=0,
% y\left(\pi /2\right)-2=0.
% The corresponding function is
% function res = bcfcn(ya,yb)
% res = [ya(1)
%        yb(1)-2];
% end
%
%% Create Initial Guess
% Use the bvpinit function to create an initial guess for the solution of the equation. Since the equation relates {y^{\prime } }^{\prime } to y, a reasonable guess is that the solution involves trigonometric functions. Use a mesh of five points in the interval of integration. The first and last values in the mesh are where the solver applies the boundary conditions.
% The function for the initial guess accepts x as an input and returns a guess for the value of y_1 and y_2. The function is
% function g = guess(x)
% g = [sin(x)
%      cos(x)];
% end

xmesh = linspace(0,pi/2,5);
solinit = bvpinit(xmesh, @guess);

%
%% Solve Equation
% Use bvp5c with the derivative function, boundary condition function, and initial guess to solve the problem.

sol = bvp5c(@bvpfcn, @bcfcn, solinit);

%
%% Plot Solution

plot(sol.x, sol.y, '-o')

%
%% Local Functions
% Listed here are the local functions that bvp5c uses to solve the equation.

function dydx = bvpfcn(x,y) % equation to solve
dydx = zeros(2,1);
dydx = [y(2)
       -y(1)];
end
%--------------------------------
function res = bcfcn(ya,yb) % boundary conditions
res = [ya(1)
       yb(1)-2];
end
%--------------------------------
function g = guess(x) % initial guess for y and y'
g = [sin(x)
     cos(x)];
end
%--------------------------------

% Copyright 2018 The MathWorks, Inc.
%