0

(edited, i have changed the code) Well i have compound equations that i need to solve in matlab and find the result. I have tried different techniques but have failed. the equations are:

u(j-1)-2(u(j))+u(j+1)= -4*h^2*pi^2 * sin(2*pi*xj)

where

n=100

j=1 to n

xj=jh

h=1/n

u(0)==u(n)==0

I need to solve the equation and plot the results. so that i can compare the results with the exact solution. This is the code i have written so far...

function c= prob1()
n=100;

c=(0);   % variable to store all results
u = linspace(1,n-1);
    for k=3:90
    jay=k;
    h=1/k;
    syms xj  
    eqn6 = u(jay-1) -2*u(jay)+u(jay+1)==-4*(h^2)*(pi^2)*sin(2*pi*xj);
    A = solve(eqn6, xj); % solving the equation with xj as unknown
      if(~(A==0))
      c=vertcat(c,A);  % just filtering out the results with 0 output
      end
    end
end

Now i GET answers in A like this " (625*asin(1/9877545463176224))/3927 ". which i cannot plot.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Hammadzafar
  • 480
  • 1
  • 7
  • 21

1 Answers1

1

Setting up the system of equations Au = b is done by translation the math into MATLAB language as follows:

n = 100;
h = 1/n;

j = 0:n; % include zero for the boundary condition
xj = j*h;

% set up right hand side
b = (-4*h^2*pi^2*sin(2*pi*xj))';
% overwrite the first and last value of b with the right hand side of the boundary conditions:
b([1 end]) = 0;

% This is the interesting part:
% set up A: 1*u(j-1) -2*u(j) + 1*u(j+1) and include the boundary conditions
main = [1; -2*ones(n-1,1); 1];
upper = [0; ones(n-1,1)];
lower = [ones(n-1,1); 0];
A = gallery('tridiag', lower, main, upper);

If you dont see why this works, I would suggest to write out the equations for at least j = 0, n/2 and n based on A and b, and to compare them with your equations.

Now, we are ready to solve the system. The system is small so I use the backslash operator (which is a direct method), but you could also pick iterative methods like bicgstab, gmres, qmr:

u = A\b;

Plot the resulting u:

plot(xj,u)
MeMyselfAndI
  • 1,320
  • 7
  • 12