简体   繁体   中英

Matrix indexing and division in Matlab

I am trying to code gauss elimination and this is the piece of code I'm using. The matrix is already triangular but there is a mistake in this expression:

x(n) = b(n) / A(n, n);

Here is the complete piece of code:

function [x] = gauss(A, b)
  n = size(A);
  for k=1 : n-1
      for i=k+1 : n
          m = A(i, k) / A(k, k);
          for j=1 : n
              A(i, j) = A(i, j) - m * A(k, j);
          end
          b(i) = b(i) - m * b(k);
      end
  end
  x(n) = b(n) / A(n, n);
  disp(double(b(n)));
  for k=n-1 : -1 : 1
      s=0;
      for i=k+1 : n
          s = s + A(k, i) * x(i);
      end
      x(k) = (b(k) - s) / A(k, k);
  end
  disp(x);
end

Thanks for your help. BTW Im a newbie in Matlab...

Edit: adding some more info

Im calling this function like this: A = [6 3 2 ; 9 -1 4 ; 10 5 3] b = [12 37 21]

sol = gauss(A, b);

This line

 n = size(A);

will have a vector result as A is a matrix. It appears that you are expecting this line

x(n) = b(n) / A(n, n);

to behave like a scalar division, but with n a vector you are actually trying to divide matrices of different dimension. Based on your example code examine the output of these statements

n = size(A);
A(n,n)
b(n)

and see that you are not dealing with scalars. If you want n to be a scalar equal to the number of rows of A try replacing

n = size(A);

with

[n n1] = size(A);

and now n should truly represent the row count of A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM