Finite Differences

In this lecture we derived the linear system for the BVP example in the text book (pages 533-534):
           2
          d u(x)           x
         -------- - ( 1 - --- ) u(x) = x
              2            5
           d x

         with u(1) = 2 and u(3) = -1
Note that the formulas in the book are not quite right...

Below is a MATLAB function (save as findif.m) which generates and solves the linear system:

function [x,u] = findif(n)
%
%  [x,u] = findif(n) applies finite differences with n subintervals
%                    to elaborate Example 7.3 on pages 533-534
%  While executing, the matrix M of the system, and right-hand side
%  vector R are displayed on screen.
%
a = 1;                      % left bound
ua = 2;
b = 3;                      % right bound
ub = -1;
h = (b-a)/n;                % step size
for i = 1:n+1               % the nodes
   x(i) = a + (i-1)*h;
end;
M = zeros(n-1,n-1);         % matrix of the linear system
for i = 1:n-1
   M(i,i) = -(2+(1-x(i+1)/5)*h^2);
   if (i < n-1)
      M(i,i+1) = 1;
   end;
   if (i > 1)
      M(i,i-1) = 1;
   end;
end;
R = zeros(n-1,1);            % right-hand side vector
R(1) = h^2*x(2)-ua;
for i = 2:n-2
   R(i) = h^2*x(i+1);
end;
R(n-1) = h^2*x(n)-ub;
M
R
u = M\R;
x = x';
u = [ua; u; ub];
For the numerical example in the text book, a run with MATLAB produces the following output:
>> [x,u] = findif(4)

M =

   -2.1750    1.0000         0
    1.0000   -2.1500    1.0000
         0    1.0000   -2.1250


R =

   -1.6250
    0.5000
    1.6250


x =

    1.0000
    1.5000
    2.0000
    2.5000
    3.0000


u =

    2.0000
    0.5520
   -0.4244
   -0.9644
   -1.0000

With 100 subintervals, we obtain a nice plot, made by the sequence of commands:
      [x,u] = findif(100);
      plot(x,u)
Follow the link to see the MATLAB plot.