%% Solve Linear System
% Solve a linear system with both mldivide and linsolve to compare performance.
% mldivide is the recommended way to solve most linear systems of equations in MATLAB ®. However, the function performs several checks on the input matrix to determine whether it has any special properties. If you know about the properties of the coefficient matrix ahead of time, then you can use linsolve to avoid time-consuming checks for large matrices.
%
% Create a 10000-by-10000 magic square matrix and extract the lower triangular portion. Set the LT field of the opts structure to true to indicate that A is a lower triangular matrix.

A = tril(magic(1e4));
opts.LT = true;

%
% Create a vector of ones for the right-hand side of the linear equation \textrm{Ax}=b. The number of rows in A and b must be equal.

b = ones(size(A,2),1);

%
% Solve the linear system \textrm{Ax}=b using mldivide and time the calculation.

tic
x1 = A\b; 
t1 = toc

%
% Now, solve the system again using linsolve. Specify the options structure so that linsolve can select an appropriate solver for a lower triangular matrix.

tic
x2 = linsolve(A,b,opts);
t2 = toc

%
% Compare the execution times to see how much faster linsolve is. As with any timing comparison, the results can vary between different computers and releases of MATLAB.

speedup = t1/t2

% Copyright 2018 The MathWorks, Inc.