how to do back substitution in matlab

Back substitution is a method used to solve systems of linear equations in the form of their upper triangular matrix. In Matlab, this can be accomplished using the "triu" function to obtain the upper part of the matrix and then using for-loops to substitute values backwards from the bottom of the matrix.

Here's an example implementation:

main.m
% Given an upper triangular matrix as A and a vector b of constants
% representing a system of linear equations Ax = b, solve for x

n = length(b);
x = zeros(n,1);

% Solve for x_n
x(n) = b(n)/A(n,n);

% Solve for x_n-1, x_n-2, ... x_1
for i=n-1:-1:1
    x(i) = (b(i) - A(i,i+1:n)*x(i+1:n))/A(i,i); % Back substitution formula
end
331 chars
14 lines

This implementation assumes that the given matrix A is an upper triangular matrix, where all entries below the main diagonal are zero.

gistlibby LogSnag