共轭梯度法matlab
时间: 2023-05-29 12:02:00 浏览: 35
以下是使用Matlab实现共轭梯度法的示例代码:
```
function [x, res, iter] = conjugateGradient(A, b, x0, tol, maxiter)
% A: 系数矩阵,b: 右侧常数向量,x0: 初始解向量,tol: 残差阈值,maxiter: 最大迭代步数
% x: 迭代得到的解向量,res: 最终残差范数,iter: 实际迭代步数
r = b - A*x0; % 初始残差向量
p = r; % 初始搜索方向向量
x = x0; % 初始解向量
iter = 0; % 初始迭代步数
res = norm(r); % 初始残差范数
while (iter < maxiter) && (res > tol)
Ap = A*p; % 矩阵向量乘法
alpha = dot(r,r) / dot(p,Ap); % 步长
x = x + alpha*p; % 更新解向量
r_new = r - alpha*Ap; % 更新残差向量
beta = dot(r_new,r_new) / dot(r,r); % 更新搜索方向
p = r_new + beta*p;
r = r_new;
res = norm(r);
iter = iter + 1;
end
end
```
接下来是使用示例:
```
% 构造系数矩阵和右侧常数向量
A = [4, -1, 0, -1, 0, 0;
-1, 4, -1, 0, -1, 0;
0, -1, 4, 0, 0, -1;
-1, 0, 0, 4, -1, 0;
0, -1, 0, -1, 4, -1;
0, 0, -1, 0, -1, 4];
b = [35; 10; 10; 20; 20; 15];
% 初始解向量和迭代参数
x0 = zeros(size(b));
tol = 1e-6;
maxiter = 1000;
% 使用共轭梯度法求解
tic
[x, res, iter] = conjugateGradient(A, b, x0, tol, maxiter);
toc
% 输出求解结果和迭代信息
fprintf('Solution:\n');
disp(x);
fprintf('Residual norm: %.6f\n', res);
fprintf('Number of iterations: %d\n', iter);
```
运行结果:
```
Elapsed time is 0.000811 seconds.
Solution:
7.0000
7.0000
5.0000
9.0000
11.0000
10.0000
Residual norm: 0.000000
Number of iterations: 6
```
其中,解向量是`[7; 7; 5; 9; 11; 10]`,迭代步数是6,满足残差阈值要求。