Thursday, March 23, 2023

Cramer's rule to solve a system of linear equations using MATLAB

Cramer's rule

Cramer's rule is a method used to solve a system of linear equations by using determinants. It is named after the Swiss mathematician Gabriel Cramer, who first published the rule in 1750.

Suppose we have a system of linear equations with n unknowns:

a11x1 + a12x2 + ... + a1nxn = b1 a21x1 + a22x2 + ... + a2nxn = b2 ... an1x1 + an2x2 + ... + annxn = bn

where aij and bi are constants. We can represent this system of equations in matrix form as:

Ax = b

where A is an n x n matrix of coefficients, x is a column vector of the unknowns, and b is a column vector of constants.

Cramer's rule states that the solution to this system of equations is given by:

xi = Det(Ai) / Det(A)

where xi is the solution to the ith unknown, Det(A) is the determinant of the matrix A, and Ai is the matrix obtained by replacing the ith column of A with the column vector b.

In other words, to find the solution to the ith unknown, we calculate the determinant of the matrix obtained by replacing the ith column of A with the column vector b, and divide it by the determinant of A.

Note that Cramer's rule only works for systems of linear equations that have a unique solution and where the determinant of A is not equal to zero. If the determinant of A is zero, the system may have no solution or an infinite number of solutions.

Let summarize it as:






















Let us apply Matlab: Here is the source code for solving equations.

=================================================

clear all, clc
% Using crammers rule to find solutions to equations
% Define the coefficient matrix A and the constant vector B
% As Ax=B
A = [-0.5 0.52 1; 0.5 1 1.9; 0.1 0.3 0.5];
B = [-0.01; 0.67; -0.44];
% Compute the determinant of A
detA = det(A)
% Compute the determinant of A with column 1 replaced by B
detA1 = det([B A(:,2:3)]) % This code joins B and A but eliminates column 1
% Compute the determinant of A with column 2 replaced by B
detA2 = det([A(:,1) B A(:,3)]) % On A it considers only column 1 and 2
% Compute the determinant of A with column 3 replaced by B
detA3 = det([A(:,1:2) B]) % here only the last column replaced by B array
% Compute the solutions using Cramer's Rule
x1 = detA1 / detA;
x2 = detA2 / detA;
x3 = detA3 / detA;
% Print the solutions to the console
fprintf('x1 = %f\n', x1);
fprintf('x2 = %f\n', x2);
fprintf('x3 = %f\n', x3);

The Matlab solver for the above code gives the following result.

==========================================================


detA =
0.0538

detA1 =
0.0328
detA2 =
-0.8719
detA3 =
0.4692
x1 = 0.609294
x2 = -16.206320
x3 = 8.721933


No comments:

Post a Comment