www.gusucode.com > matlab 案例源码 matlab代码程序 > matlab/SolveLinearSystemExample.m

    %% Solve Linear System
% Examine why solving a linear system by inverting the matrix using
% |inv(A)*b| is inferior to solving it directly using the backslash
% operator, |x = A\b|.

%%
% Create a random matrix |A| of order 500 that is constructed so that its
% condition number, |cond(A)|, is |1e10|, and its norm, |norm(A)|, is |1|.
% The exact solution |x| is a random vector of length 500, and the
% right side is |b = A*x|. Thus the system of linear equations is
% badly conditioned, but consistent.
n = 500; 
Q = orth(randn(n,n));
d = logspace(0,-10,n);
A = Q*diag(d)*Q';
x = randn(n,1);
b = A*x;

%%
% Solve the linear system |A*x = b| by inverting the coefficient matrix
% |A|. Use |tic| and |toc| to get timing information.
tic
y = inv(A)*b; 
t = toc

%%
% Find the absolute and residual error of the calculation.
err_inv = norm(y-x)

%%
res_inv = norm(A*y-b)

%%
% Now, solve the same linear system using the backslash operator |\|.
tic
z = A\b;
t1 = toc

%%
err_bs = norm(z-x)

%%
res_bs = norm(A*z-b)

%%
% The backslash calculation is quicker and has less residual error by
% several orders of magnitude. The fact that |err_inv| and |err_bs| are
% both on the order of |1e-6| simply reflects the condition number of the
% matrix.
%
% The behavior of this example is typical. Using |A\b| instead of
% |inv(A)*b| is two to three times faster, and produces residuals on the
% order of machine accuracy relative to the magnitude of the data.