Search code examples
matlabmatrixdimensionsequation-solvinglinear-equation

Matrix dimensions error when using norm()


I'm trying to use MATLAB to run Richardson's iteration for computing the solution of a linear system, Ax=b. I wrote a function to do this, but got an error when I tried to run it. The following is my function where x0 is the initial iterate, L is the maximum number of iterations, A is a nonsingular nxn matrix, b is a n-length vector, a is in place of the alpha parameter required for the algorithm, tol is the desired level of precision, x is a n-length vector, and k is the actual number of iterations:

function [x,k]=Richardson(x0,L,A,b,a,tol)
n = size(b);
x1 = x0 + a*(b-A*x0);
Norm = norm(x1-x0)/sqrt(n);
k = 1;
x0 = x1;
while (Norm > tol) && (k < L)
    x1 = x0 + a*(b-A*x0);
    Norm = norm(x1-x0)/sqrt(n);
    k = k + 1;
    x0 = x1;
end
x = x1;

I tried to run this function using the following:

x0=[0;0;0];
L = 10;
A=[1,0,0;0,2,0;0,0,4];
b=[1;1;1];
a=-1;
tol=10.^(-5);

a1=Richardson(x0,L,A,b,a,tol)

This was the error I got:

Error using  / 
Matrix dimensions must agree.

Error in Richardson (line 4)
Norm = norm(x1-x0)/sqrt(n);

Error in HW8 (line 11)
a1=Richardson(x0,L,A,b,a,tol)

I don't see how this is the case, because x0 and x1 are both n-length vectors. Am I implementing this incorrectly?


Solution

  • n = size(b);
    

    Results in a 2 values vector (3,1 in your case). So you can't divide a single value by 2 values. Change to n = size(b,1) or n=size(b,2) to get what you need (rows or columns).