Page 238 - MATLAB an introduction with applications
P. 238
Numerical Methods ——— 223
k = 1;, diff = [];
while k< = kmax
xnew = b;
for i = 1:n
for j = 1:n
if j~ = i
xnew(i) = xnew(i) – A(i,j) xold(j);
*
end
end
xnew(i) = xnew(i)/A(i,i);
end
diff(k) = norm(xnew-xold,2);
if diff(k)<tol
fprintf(‘Jacobi iteration has converged in %d iterations.\r’, k)
x = xnew;
return
end
k = k+1;, xold = xnew;
end
fprintf(‘Jacobi iteration failed to converge.\r’)
x = xnew;
Example E4.8: Find the solution to the equations using Jacobi method with initial values [0 0 0 0].
42 00 4
x
1
28 2 0
0
x
=
2
02 8 2
0
x
3
x
0024 0
4
Solution:
>> A = [4 2 0 0;2 8 2 0;0 2 8 2;0 0 2 4];
>> b = [4;0;0;0];
>> x0 = [0 0 0 0]’;
>> [x,k] = jacobi(A,b,x0,1.e – 10)
Jacobi iteration has converged in 34 iterations.
x =
1.1556
–0.3111
0.0889
–0.0444