matlab jacobi迭代方法,给我矩阵维度必须同意

时间:2015-09-19 01:17:37

标签: matlab matrix

下面是我执行jacobi迭代以解决Ax = b的代码。 我在矩阵A =[4 -1 1; 4 -8 1; -2 1 5]b=[7 -21 15]上尝试使用此代码。 x是第一个猜测1 x 3向量。这些尺寸不正确吗?它给出了计算代码中的错误:r = b - x*AM\(x*N + b)

我错过了什么?!?我该如何解决?请帮忙!

function [x, error, iter, flag] = jacobi(A, x, b, maxiter, tol)

%implement jacobi iterations
%[x, error, iter, flag] = jacobi(A, x, b, maxiter, tol)
%jacobi.m solves the linear system Ax=b using the Jacobi iteration
%
%
%INPUT A       the matrix of the system Ax=b
%      x       the first guess vector Ax=b
%      b       the vector in the system
%      maxiter the maximum number of iteration to perform
%      tol     the tolerance
%
%OUTPUT x      the solution vector
%       error  error norm
%       niter  the number of iterations it took
%       flag   indicates whether a solution was found. 0 means there was a
%              solution and 1 means there was not a solution
iter = 0;
flag = 0;

bnrm2 = norm(b);
if (bnrm2 == 0)
     bnrm2 = 1.0; 
end

r = b - x*A;
error = norm(r) / bnrm2;
if (error<tol) 
    return; 
end

[m,n] = size(A);

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

for iter = 1:maxiter,
    oldx = x;
    x = M\(x*N + b);

    error = norm(x - oldx) / norm(x);
    if (error <= tol)
        break;
    end
end
if (error > tol) 
     flag = 1; 
end

1 个答案:

答案 0 :(得分:0)

因为,在代码中,你正在解决我将要调用的东西(不确定它是否合适,因为我从来没有这样做)左乘法问题,在某种意义上,运算符和矩阵的顺序是相反的。

如果您使用剩余A*x = b解决问题r = b - A*x(即xb是列向量),您将执行右向量乘法并离开-matrix分裂。因此,循环中的更新行将是

x = M \ (N*x + b);

相反,如果您使用剩余x*A = b解决问题r = b - x*A(即xb是行向量),您将执行左向量乘法和右矩阵划分。因此,循环中的更新行将是

x = (x*N + b) / M;

请注意\解析为mldivide函数,/解析为mrdivide。乘法没有函数区别。

看来你当前的更新程序混合了两者,这对于尺寸匹配来说是坏消息。