Vous êtes sur la page 1sur 8

function HW4_main_RINWA

% Input values for finite difference method


N = 16;
% N steps
a = 0.5;
% alpha value alpha value from neumann
boundary condition
h = 1/N;
% step size of the meshgrid
x = [0:h:1];
% meshgrid divided into h steps
y =-1/6.*x.^3+x;
% exact solution
[A,f,u] = fin(N,a,h,x,y);
% calling the funtion
% displaying the results from the finite difference method
disp('The global matrix A^h is: ')
A
disp('The right hand side vector f is: ')
f
disp('The numerical solution vector u is: ')
u
end
function [A,f,u] = fin(N,a,h,x,y)
% constructing the global A matrix
A = full(spdiags([-1*(1/h^2)*ones(N+1,1) 2*(1/h^2)*ones(N+1,1) -1*(1/
h^2)*ones(N+1,1)],-1:1,N+1,N+1)); % setting up the matrix using
spdiag command
A(1,:) = [1,zeros(1,N)];
% interchanging the first row of A to implement the left
boundary condition
A(N+1,:) = [zeros(1,N-1) -1*1/h^2 1*1/h^2];
% interchanging the last row of A to implement the right
boundary condition
f = [x(1:N) x(length(x))+(a/h)]';
% setting up the right
hand vector f including the error (alpha/h for the last element)
u = A\f;
% computing the u vector
(solution vector)
% setting up the plot - comparison between exact solution and
approximate
% numerical solution computed with the finite difference method
figure(1)
plot(x,u,'*',x,y,'-')
title('Numerical approximation for ODEs using finite difference method
vs. Exact solution')
ylabel('[u] value')
legend('Approximate (numerical) solution','Exact (analytical)
solution')
xlabel('[x] value/meshgrid')
end
The global matrix A^h is:
A =
Columns 1 through 13

1
0

512

-256

-256

512

-256

-256

512

-256

-256

512

-256

-256

512

-256

-256

512

-256

-256

512

-256

-256

512

-256

-256

512

-256

-256

512

-256

0
-256

0
0

0
0

0
0

0
0

0
0

0
0

0
0

0
0

0
0

-256

0
0

512

-256
0

-256
0

0
-256
0
0
0
0
0
0

512

0
0
0

Columns 14 through 17
0
0
0
0
0
0
0
0
0
0
0
0
-256
512
-256
0

0
0
0
0
0
0
0
0
0
0
0
0
0
-256
512
-256

0
0
0
0
0
0
0
0
0
0
0
0
0
0
-256
512

0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
-256

-256

256

The right hand side vector f is:


f =
0
0.0625
0.1250
0.1875
0.2500
0.3125
0.3750
0.4375
0.5000
0.5625
0.6250
0.6875
0.7500
0.8125
0.8750
0.9375
9.0000
The numerical solution vector u is:
u =
0
0.0645
0.1287
0.1924
0.2554
0.3174
0.3782
0.4375
0.4951
0.5508
0.6042
0.6553
0.7036
0.7490
0.7913
0.8301
0.8652

Published with MATLAB R2015b

STOpgNT

ILv^

iM

I^CJL)

lOo.'.-^

4^77 / g> (f

>^6^^c>^

./

/fx,-)

v. '

^ 5 ^ - < A/

u -

fi =

0
0

IE

-i

Vous aimerez peut-être aussi