Path: news.mathworks.com!not-for-mail
From: "James Tursa" <aclassyguywithaknotac@hotmail.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Cramer's Rule - linear equations
Date: Wed, 14 May 2008 07:53:01 +0000 (UTC)
Organization: Boeing
Lines: 66
Message-ID: <g0e5ot$96$1@fred.mathworks.com>
References: <g0bdna$rjm$1@fred.mathworks.com>
Reply-To: "James Tursa" <aclassyguywithaknotac@hotmail.com>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1210751581 294 172.30.248.37 (14 May 2008 07:53:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 14 May 2008 07:53:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 756104
Xref: news.mathworks.com comp.soft-sys.matlab:468295


"Ashwini Deshpande" <vd.ashwini@mathworks.com> wrote in
message <g0bdna$rjm$1@fred.mathworks.com>...
> I have three linear equations with 3 unknowns, say for
example:
> 
> 3x + 4y + 6z = 1; 
> x - 2y + 7z = 10;
> 2x + 3y - 9z = 15;
> 
> How do i solve this using matlab, is there any easiest way
> to apply Cramer's Rule to Solve these equations ???
> 
> Any help would be appreciated !!
> Thanks !
> Ashwini
> 

If you want to learn why Cramer's Rule is not a very good
method numerically and why it is avoided, particularly for
large problems, consider the code below and try it for
inputs of 100, 200, 300, 400, 500, 600. The intermediate
numbers get huge (eventually blows up), the timings get very
long, and it is not as accurate as the built in MATLAB \
operator. Like I said, it's slow, but it's inaccurate.

James Tursa

------------------------------

function callcramer(m)
disp(' ');
A = rand(m,m);
b = rand(m,1);
disp('Timing backslash:');
tic
x = A\b;  % Backslash operator for solving A*x = b
toc
xc = cramersrule(A,b);
disp(['norm of backslash residual     = '
num2str(norm(A*x-b),4)]);
disp(['norm of Cramer''s Rule residual = '
num2str(norm(A*xc-b),4)]);
disp(' ');
return
end

function x = cramersrule(A,b)  % Demo of Cramer's Rule for
solving A*x = b
disp('Timing Cramer''s Rule:');
tic
[m n] = size(b);
z = zeros(m,1);
Ai = A;
for k=1:m
    Ai(:,k) = b;
    z(k) = det(Ai);
    Ai(:,k) = A(:,k);
end
detA = det(A);
x = z / detA;
toc
disp(['Max abs(det(Ai)) = ' num2str(max(abs(z)),4)]);
disp(['abs(det(A))      = ' num2str(abs(detA),4)]);
return
end