%% Row Reduction of Augmented Matrices
% Use Gauss-Jordan elimination on augmented matrices to solve a linear system and calculate the matrix inverse. These techniques are mainly of academic interest, since there are more efficient and numerically stable ways to calculate these values.
%
% Create a 3-by-3 magic square matrix. Add an additional column to the end of the matrix. This augmented matrix represents a linear system \textrm{Ax}=b, with the extra column corresponding to b.

A = magic(3);
A(:,4) = [1; 1; 1]

%
% Calculate the reduced row echelon form of A. Index into R to extract the entries in the extra (augmented) column, which contains the solution to the linear system.

R = rref(A)
x = R(:,end)

% A more efficient way to solve this linear system is with the backslash operator, x = A\b.
%
% Create a similar magic square matrix, but this time append an identity matrix of the same size to the end columns.

A = [magic(3) eye(3)]

%
% Calculate the reduced row echelon form of A. In this form the extra columns contain the inverse matrix for the 3-by-3 magic square matrix.

R = rref(A)
inv_A = R(:,4:end)

% A more efficient way to calculate the inverse matrix is with inv(A).
%
% Copyright 2018 The MathWorks, Inc.