Applying Cramer's rule on an nxn matrix

31 vues (au cours des 30 derniers jours)
Rune
Rune le 10 Oct 2013
I need to find the solution to a system Ax=b using Cramer's rule. It needs to be Cramer's rule. I have made the following code that works for a 3x3 matrix, but i want it to work for an nxn matrix using a for-loop.
I can't figure out how to write the loop.
Thank you very much in advance!
n=3; d=10;
A = floor(d*rand(n,n)); b = randi(d,n,1);
D_A = det(A);
A_1 = A;
A_1(1) = b(1);
A_1(2) = b(2);
A_1(3) = b(3);
D_A_1 = det(A_1);
x1 = D_A_1/D_A;
A_2 = A;
A_2(4) = b(1);
A_2(5) = b(2);
A_2(6) = b(3);
D_A_2 = det(A_2);
x2 = D_A_2/D_A;
A_3 = A;
A_3(7) = b(1);
A_3(8) = b(2);
A_3(9) = b(3);
D_A_3 = det(A_3);
x3 = D_A_3/D_A;

Réponses (2)

Roger Stafford
Roger Stafford le 10 Oct 2013
Modifié(e) : Roger Stafford le 10 Oct 2013
The two basic operations in applying Cramer's rule are: 1) replacing the k-th column of A by b and 2) obtaining the determinant of the various matrices which this produces, as well as the determinant of A. Hopefully you are allowed to use the matlab function 'det' for the latter purpose. The former one is accomplished in two steps by
A_k = A;
A_k(:,k) = b;
Of course you need to use a for-loop in order to do this for each k.

Ali Jadoon
Ali Jadoon le 24 Mar 2014
Try this m file. It is general code for any size matrix to generate the output File ID: #45930

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by