1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| function [ output_args ] = cqj_Jacobi(init_X,coefficient_mat,b_mat,maxNum,epsilon)
output_args = []; flag = 0;
if size(coefficient_mat,1) ~= size(coefficient_mat,2) disp('系数矩阵格式错误(需要方阵)'); return; end if size(b_mat,1) ~= 1 && size(b_mat,2) ~= 1 disp('AX=b中的b必须为行向量或者列向量'); return; end if size(b_mat,1) == 1 b_mat = b_mat'; end if size(init_X,1) ~= 1 && size(init_X,2) ~= 1 disp('初始值必须为行向量或者列向量'); return; end if size(init_X,1) == 1 init_X = init_X'; end if size(init_X,1) ~= size(coefficient_mat,1) disp('初始值与系数矩阵维数不一致'); return; end if size(init_X,1) ~= size(b_mat,1) disp('AX=b中的b向量维数错误(需与系数矩阵的维数一致'); return; end if ~exist('maxNum', 'var') maxNum = 500; end if ~exist('epsilon', 'var') epsilon = 1e-14; end
D = diag(diag(coefficient_mat));
D_inv = diag(1./diag(coefficient_mat));
x = init_X;
for k = 1:maxNum temp = D_inv*(b_mat-(coefficient_mat-D)*x); if norm(temp-x) < epsilon flag = 1; x = temp; break; end x = temp; end
text(0,0.95,'方程:','Color','red','FontSize',14); str1 = '\left[\begin{array}';
str2 = @(X) regexprep(regexprep(mat2str(zeros(1,size(X,2))),... '[\s\[\]]',''),'0','c'); mat_start = @(X) [str1 '{' str2(X) '}']; my_mat2str = @(mat) regexprep(regexprep(regexprep(mat2str(mat),... ' *','&'),';','\\\'),'[\[\]]',''); mat_end = '\end{array}\right]'; str5 = '\times X=';
text('Interpreter','latex', 'String',['$$'... mat_start(coefficient_mat),my_mat2str(coefficient_mat),mat_end,... str5,mat_start(b_mat),my_mat2str(b_mat),mat_end '$$'],... 'Position',[0.1 0.7],'FontSize',10); text(0,0.5,'标准雅可比迭代结果:','Color','red','FontSize',14); if flag == 1 output_args.itrNum = k; output_args.result = x; fprintf('迭代次数:%d\n',output_args.itrNum);
disp('解:'); disp(x); text('Interpreter','latex', 'String',['$$X^*=' ... mat_start(x) my_mat2str(x) mat_end '$$'],... 'Position',[0.1 0.3],'FontSize',10); text(0.1,0.1,['迭代次数:' num2str(output_args.itrNum)],... 'Color','k','FontSize',10); return; end text(0.1,0.3,['迭代' num2str(maxNum) '次后未收敛'],... 'Color','k','FontSize',10); fprintf('迭代%d次后暂未收敛\n',maxNum); end
|