Search code examples
matlabmathmatrixdifferential-equations

2nd Order ODE Approx using Finite Difference


I am trying to approximate and plot the solution to u"(x) = exp(x) in the interval 0-3, with boundary conditions x(0)=1,x(3)=3. I am able to plot the approximate solution vs the exact, but the plot looks a bit off:

% Interval
a=0;
b=3;
n=10;

% Boundary vals
alpha=1;
beta=3;
%grid size
h=(b-a)/(n+1); 


%Matrix generation
m = -2;
u = 1;
l = 1;

% Obtained from (y(i-1) -2y(i) + y(i+1)) = h^2 exp(x(i)


M = (1/h^2).*(diag(m*ones(1,n)) + diag(u*ones(1,n-1),1) + diag(l*ones(1,n-1),-1));

B=[];
xjj=[];


for j=1:n
    xjj=[xjj,j*h];
    if j==1
        B=[B,f(j*h)-(alpha/h^2)];

        continue 
    end
    if j==n
        B=[B,f(j*h)-(beta/h^2)];
        continue 
    else
        B=[B,f(j*h)];
    end
end

X=M\B';



x=linspace(0,3,101);
plot(xjj',X,'r*')
hold on 
plot(x,exp(x),'b-')

I appreciate all the advice and explanation. This is the scheme I am following: http://web.mit.edu/10.001/Web/Course_Notes/Differential_Equations_Notes/node9.html


Solution

  • You could shorten the big loop to simply

    x=linspace(a,b,n+2); 
    B = f(x(2:end-1)); 
    B(1)-=alpha/h^2; 
    B(n)-=beta/h^2;
    

    The exact solution is u(x)=C*x+D+exp(x), the boundary conditions give D=0 and 3*C+exp(3)=3 <=> C=1-exp(3)/3.

    Plotting this exact solution against the numerical solution gives a quite good fit for this large step size:

    enter image description here

    f=@(x)exp(x)
    a=0; b=3;
    n=10;
    
    % Boundary vals
    alpha=1; beta=3;
    %grid 
    x=linspace(a,b,n+2); 
    h=x(2)-x(1); 
    
    % M*u=B obtained from (u(i-1) -2u(i) + u(i+1)) = h^2 exp(x(i))
    M = (1/h^2).*(diag(-2*ones(1,n)) + diag(1*ones(1,n-1),1) + diag(1*ones(1,n-1),-1));
    B = f(x(2:end-1)); 
    B(1)-=alpha/h^2; B(n)-=beta/h^2;
    
    U=M\B';
    
    U = [ alpha; U; beta ];
    clf;
    plot(x',U,'r*')
    hold on 
    x=linspace(0,3,101);
    C = 1-exp(3)/3
    plot(x,exp(x)+C*x,'b-')