CS计算机代考程序代写 A = [2 -1 0; -1 2 -1;0 -1 2];

A = [2 -1 0; -1 2 -1;0 -1 2];
c = [1;4;7];

A\c
%%
% Jacobi Method

A = [2 -1 0; -1 2 -1;0 -1 2];
c = [1;4;7];

M = diag(diag(A))
N = M-A

x = [1;0;0];
i = 1;
tol = 10^-6;

%fprintf(‘ x1 x2 x3 \n’)
%fprintf(‘%10.7f %10.7f %10.7f\n’,x(1),x(2),x(3))

while norm(A*x-c,2)>tol
x = M^-1*(N*x+c);
%fprintf(‘%10.7f %10.7f %10.7f\n’,x(1),x(2),x(3))
i = i+1;
end

x

fprintf(‘Iteration was completed in %d iterations’,i)
%%
% Gauss-Seidel

A = [2 -1 0; -1 2 -1;0 -1 2];
c = [1;4;7];

M = tril(A)
N = M-A

x = [1;0;0];
i = 1;
tol = 10^-6;

%fprintf(‘ x1 x2 x3 \n’)
%fprintf(‘%10.7f %10.7f %10.7f\n’,x(1),x(2),x(3))

while norm(A*x-c,2)>tol
x = M^-1*(N*x+c);
%fprintf(‘%10.7f %10.7f %10.7f\n’,x(1),x(2),x(3))
i = i+1;
end

x

fprintf(‘Iteration was completed in %d iterations’,i)
%%
% Spectral Radius

A = [2 -1 0; -1 2 -1;0 -1 2];
c = [1;4;7];

D = diag(diag(A));
U = triu(A)-D;
L = A-D-U;
j = 1;

w = 0:0.01:2
rho=zeros(length(w),1);

for i = 1:length(w)

rho(j) = max(abs(eig(inv(D+w(i)*L)*(-(w(i)*U+(w(i)-1)*D)))));
j=j+1;
end

plot(w,rho)
xlabel(‘\omega’)
ylabel(‘\rho’)

fprintf(‘The minimum occurs at ~ %f’,w(find(rho==min(rho))))
%%
% SOR

A = [2 -1 0; -1 2 -1;0 -1 2];
c = [1;4;7];

D = diag(diag(A))
U = triu(A)-D
L = A-D-U

w = 1.18;

x = [1;0;0];
i = 1;
tol = 10^-6;
max_iter = 5000;

%fprintf(‘ x1 x2 x3 \n’)
%fprintf(‘%8.3f %8.3f %8.3f\n’,x(1),x(2),x(3))

while norm(A*x-c,2)>tol && i