Home > Net >  MatLab Triangular system of linear equations
MatLab Triangular system of linear equations

Time:03-31

I have a problem with MatLab in Octave I need to make a program, which solves a Triangular system of linear equations, using back substitution method (https://i.stack.imgur.com/ETPxn.png) I have a problem with my code, Octave displays this error:

error: =: nonconformant arguments (op1 is 1x1, op2 is 2x2)
error: called from
backsub at line 6 column 10
prog31 at line 3 column 1
run at line 93 column 5

Here is my code:

Backsub function (backsub.m)

function X = backsub(A,B)
  n = length(B);
  X = zeros(n, 1);
  X(n) = B(n)./A(n,n);
  for k = n-1:-1:1
    X(k) = (B(k)-A(k,k 1:n) X(k 1:n))./A(k,k);
end

Main function (prog31.m)

A = [3 -2 1 -1; 0 4 -1 2; 0 0 2 3; 0 0 0 5];
B = [8; -3; 11; 15];
X = backsub(A, B);
disp(X);

CodePudding user response:

You mistyped * as in the for-loop, hence the error. This is the fix:

function X = backsub(A,B)
  n = length(B);
  X = zeros(n, 1);
  X(n) = B(n)/A(n,n); % remove . because A(n,n) is scalar
  for k = flip(1:n-1)
    X(k) = (B(k)-(A(k,k 1:n)*X(k 1:n)))/A(k,k); % remove . and replace   with *
  end % end the for loop
end

As a side note: The product in the for-loop is a dot product, because A(k,k 1:n) is a row vector while X(k 1:n) is a column vector of appropriate size. If you want to use provided formula verbatim (with the sigma sum), it would be

X(k) = (B(k)-sum(A(k,k 1:n)'.*X(k 1:n)))/A(k,k);
  • Related