%% Solve Linear System with LU Factorization
% Solve a linear system by performing an LU factorization and using the factors to simplify the problem. Compare the results with other approaches using the backslash operator and decomposition object.
%
% Create a 5-by-5 magic square matrix and solve the linear system \textrm{Ax}=b with all of the elements of b equal to 65, the magic sum. Since 65 is the magic sum for this matrix (all of the rows and columns add to 65), the expected solution for x is a vector of 1s.

A = magic(5);
b = 65*ones(5,1);
x = A\b

%
% For generic square matrices, the backslash operator computes the solution of the linear system using LU decomposition. LU decomposition expresses A as the product of triangular matrices, and linear systems involving triangular matrices are easily solved using substitution formulas.
% To recreate the answer computed by backslash, compute the LU decomposition of A. Then, use the factors to solve two triangular linear systems:
% y = L\(P*b);
% x = U\y;
% This approach of precomputing the matrix factors prior to solving the linear system can improve performance when many linear systems will be solved, since the factorization occurs only once and does not need to be repeated.

[L,U,P] = lu(A)

%

y = L\(P*b);
x = U\y

%
% The decomposition object also is useful to solve linear systems using specialized factorizations, since you get many of the performance benefits of precomputing the matrix factors but you do not need to know how to use the factors. Use the decomposition object with the 'lu' type to recreate the same results.

dA = decomposition(A,'lu');
x = dA\b

% Copyright 2018 The MathWorks, Inc.