A = [10 -1 -2; -1 10 -2; -1 -1 5]; b = [7.2; 8.3 ; 4.2]; max_iter = 30; tol = 1.0e-6; % [x,iter] = jacobi(A,b,max_iter,tol); [x,iter] = GS(A,b,max_iter,tol); %% Jacobi method % A: 矩阵 % b: 右端项 % max_iter: 最大迭代步数 function [x,iter] = jacobi(A,b,max_iter,tol) n = size(A,1); x = zeros(n,1); x_pre = x; iter = 0; while iter < max_iter for i = 1:n x(i) = b(i); for j = 1:n x(i) = x(i) - A(i,j)*x_pre(j); end x(i) = x(i) + A(i,i)* x_pre(i); x(i) = x(i) / A(i,i); end err = norm(A*x-b,Inf); fprintf('Step %d Error = %.2e\n',iter, err); if err < tol break; end x_pre = x; iter = iter +1 ; end end %% Gauss-Seidel method % A: 矩阵 % b: 右端项 % max_iter: 最大迭代步数 function [x,iter] = GS(A,b,max_iter,tol) n = size(A,1); x = zeros(n,1); iter = 0; while iter < max_iter for i = 1:n x(i) = b(i); for j = 1:i-1 x(i) = x(i) - A(i,j)*x(j); end for j = i+1:n x(i) = x(i) - A(i,j)*x(j); end %x(i) = x(i) + A(i,i)* x(i); x(i) = x(i) / A(i,i); end err = norm(A*x-b,Inf); fprintf('Step %d Error = %.2e\n',iter, err); if err < tol break; end iter = iter +1 ; end end如何给这段代码加上初值x0
时间: 2024-02-14 13:24:44 浏览: 104
可以在函数定义时增加一个参数x0,表示初始值,然后在迭代过程中将x_pre初始化为x0即可。修改后的代码如下:
%% Jacobi method
% A: 矩阵
% b: 右端项
% max_iter: 最大迭代步数
% tol: 收敛精度
% x0: 初始值
function [x,iter] = jacobi(A,b,max_iter,tol,x0)
n = size(A,1);
x = x0; % 将初始值赋给x
x_pre = x;
iter = 0;
while iter < max_iter
for i = 1:n
x(i) = b(i);
for j = 1:n
if j ~= i
x(i) = x(i) - A(i,j)*x_pre(j);
end
end
x(i) = x(i) / A(i,i);
end
err = norm(A*x-b,Inf);
fprintf('Step %d Error = %.2e\n',iter, err);
if err < tol
break;
end
x_pre = x;
iter = iter +1 ;
end
end
%% Gauss-Seidel method
% A: 矩阵
% b: 右端项
% max_iter: 最大迭代步数
% tol: 收敛精度
% x0: 初始值
function [x,iter] = GS(A,b,max_iter,tol,x0)
n = size(A,1);
x = x0; % 将初始值赋给x
iter = 0;
while iter < max_iter
for i = 1:n
x(i) = b(i);
for j = 1:i-1
x(i) = x(i) - A(i,j)*x(j);
end
for j = i+1:n
x(i) = x(i) - A(i,j)*x_pre(j);
end
x(i) = x(i) / A(i,i);
end
err = norm(A*x-b,Inf);
fprintf('Step %d Error = %.2e\n',iter, err);
if err < tol
break;
end
iter = iter +1 ;
end
end
调用时只需要传入一个初始值即可:
x0 = [1;2;3];
[x_jacobi, iter_jacobi] = jacobi(A, b, max_iter, tol, x0);
[x_gs, iter_gs] = GS(A, b, max_iter, tol, x0);
阅读全文