Lab# 05
Introduction to Function File
and Execution of Cramer Rule
on MATLAB
Introduction to Function File
You can save your function:
In a function file which contains only function definitions. The name of the file must match the
name of the first function in the file.
In a script file which contains commands and function definitions. Script files cannot have the
same name as a function in the file.
Files can include multiple local functions or nested functions. For readability, use the end keyword to
indicate the end of each function in a file. The end keyword is required when:
Any function in the file contains a nested function.
The function is a local function within a function file, and any local function in the file uses the
end keyword.
The function is a local function within a script file.
Procedure to Execute Codes in Function File
First open MATLAB.
Then go to the menu.
Then click on the ‘NEW’.
From ‘NEW’ select the ‘FUNCTION’ and this lead to the opening of editor.
On editor write the Function code and save the Untitled file.
Then call the command window and write the calculation formula.
Introduction to Cramer Rule
Cramer’s rule is one of the important methods applied to solve a system of equations. In this method,
the values of the variables in the system are to be calculated using the determinants of matrices. Thus,
Cramer’s rule is also known as the determinant method.
This is the most commonly used formula for getting the solution for the given system of equations
formed through matrices. The solution obtained using Cramer’s rule will be in terms of the determinants
of the coefficient matrix and matrices obtained from it by replacing one column with the column vector
of the right-hand sides of the equations.
Procedure
Here’s a step-by-step guide to implement this in MATLAB:
Step 1: Define matrix A and vector B
A = input('Enter a coefficient matrix')
B = input('Enter a source vector:')
Step 2: Calculate the determinant of A
detA = det(A);
Step 3: Check if detA is not zero
if detA == 0
error('The system has no unique solution (determinant is zero).');
end
Step 4: Apply Cramer’s Rule
n = length(B);
X = zeros(n,1); % Initialize solution vector
for i = 1:n
Ai = A;
Ai(:,i) = B; % Replace i-th column with B
X(i) = det(Ai)/detA;
end
Step 5: Display the result
disp('Solution vector X is:');
disp(X);