# finite difference method code

20 views (last 30 days)
Ronald Aono on 4 Nov 2019
Answered: Walter Roberson on 4 Nov 2019
% set domains limits and boundary conditions
xo = pi/2; xf = pi; yxo = 1; yxf = 1; N = 10;
% compute interval size and discrete x vector
dx = (xf-xo)/N; dx2 = dx*dx; x = (xo+dx):dx:xf;
% analytica solution (exact)
xe = linspace(xo,xf,N);
ye = (pi./(2*xe)).*(sin(xe) - 2*cos(xe));
% arranging the matrix a
%node 1
a(1,1)=dx2-2; a(1,2)=1+(dx/(xo+dx)); b(1)= ((yxo*dx) /(xo*dx))-yxo;
for i = 2:N-1
a(i,i-1) = (1-(dx/x(i)));
a(i,i) = dx2-2;
a(i,i+1) = (1+(dx/x(i)));
b(i)=0;
end
a(N,N-1)=(2*xf+2*dx)/xf; a(N,N-2)=-1; b(N)=yxf*dx2+yxf+((2*yxf*dx)/xf);
yi=a\b;
i keep getting the following error code
finite_1
Error using \
Matrix dimensions must agree.
Error in finite_1 (line 26)
yi=a\b

Walter Roberson on 4 Nov 2019
• If A is a rectangular m-by-n matrix with m ~= n, and B is a matrix with m rows, then A\B returns a least-squares solution to the system of equations A*x= B.
Your A is 10 x 10, and your b is 1 x 10, which has 1 row, rather than the 10 rows needed to match the 10 rows of a
It would be legal to use a\b' but you will need to decide whether that is meaningful for your situation.