TITLE: Using collocation method to solve a nonlinear boundary value ODE
QUESTION [7 upvotes]: I have the following ODE 
$$ u'' = -(1 + e^u), \quad u(0)=0,\quad u(1)=1$$
I want the divide the interval $[0,1]$ into $n-1$ equal subintervals each with length $h=1/(n-1)$ and we take approximate solution 
$$ v(t,x) = \sum_{i=1}^{n} x_i t^{i-1} $$
polynomial of degree $n-1$ sothat $v(0,x)=0$ and $v(1,x)=1$, (boundary conditions are to be satisfied).
So, our goal is to determine $x_2,x_3,...,x_{n-1}$  interior points since we already know $x_1 = 0$. Once these are found, then we have an approximation to our true solution $u(t) \approx v(t,x)$.
My question is, how can we implement this in matlab? because solving such system is quite time consuming by hand.

REPLY [6 votes]: The polynomial can be determined for instance with the code (in octave, there might be slight differences for matlab).

First define a function that takes a coefficient array and returns an  array containing the boundary conditions and the ODE residuals at the collocation points.
function f = system(c)
  % degree of the interpolating polynomial
  % is also the number of subdivisions
  deg = length(c)-1;
  f = zeros(1,deg+1);
  % left boundary condition
  f(1)=polyval(c,0);
  % second derivative of polynomial
  c2 = polyder(polyder(c));
  % enforce differential equation at inner points
  for k = 1:deg-1
    xk = k*1.0/deg;
    f(k+1)= polyval(c2,xk) + (1+exp(polyval(c,xk)));
  end
  % right boundary condition
  f(deg+1)=polyval(c,1) - 1;
end

This nonlinear system function can now be called in fsolve where the initialization array also determines the degree of the collocation polynomial
clf;
% define target accuracy
options = optimset("TolX", 1e-9, "TolFun", 1e-6);
% number of subdivisions = polynomial degree
deg = 5;
hold on;
% loop over different initializations to find multiple solutions
for k = 0:5
   c = zeros(1,deg+1);
   c(deg) = 1+3*k; c(deg-1) = -3*k;
   % log the initial coefficients
   c
   % solve system and log the result
   c = fsolve(@(c) system(c), c, options)
   % plot the solution
   x = linspace(0,1,101);
   plot(x, polyval(c,x))
end
hold off;


The execution of this code finds two solutions, which are repeated 3 times for the chosen initializations:
 0.24661  -0.38053    -0.31725   -1.02286    2.47402    0.00000
30.41419  -49.23356   11.70577   -1.37713    9.49074    0.00000

with the plot


Addendum: Taking the degree 2 solutions as in the answer of Harry49
 -1.78945    2.78945    0.00000
 -9.61015   10.61015    0.00000

and using these polynomials and their derivative to initialize the BVP solver (in python, as my version of octave does not have this functionality), gives the following plot, where the polynomials are drawn in gray below the more exact solutions: