Create an m-file mydet.m to compute the determinant of a square matrix using rec
ID: 3109286 • Letter: C
Question
Create an m-file mydet.m to compute the determinant of a square matrix using recursion. The function should take as input a matrix A and return its determinant d. Test your code on the following matrix and use det (middot) to check your answer. B = [-7 4 -2 -8 6 8 7 2 3 -1 6 -6 6 0 -7 -6 2 -9 2 0 -9 6 7 5 0] Approach: Computing the determinant using recursion: The determinant of an n times n square matrix A can be calculated in the following way: det(A) = a_11 C_11 + a_12 + ... + a_1n C_1n where C_1j = (-1)^1 + j det(M_1j) and the (n - 1) times (n - 1) submatrix M_1j of A throws out row 1 and column j.Explanation / Answer
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include<process.h>
void main()
{
int determinant(int[5][5],int);// FUNCTIONS
void read(int[5][5],int);
void print(int[5][5],int); // PROTOYPES
int a[5][5],l,n;
int result;
l1:clrscr();
cout<<"
ENTER ORDER OF MATRIX(MAX. OF 4X4):";
cin>>l>>n;
if(l!=n)
{ //TESTING CONDITION
cout<<"
SORRY!!!!! ONLY SQUARE MATRIX";
goto l1;
}
read(a,n);
result = determinant(a,n);
print(a,n);
cout<<"
THE DETERMINANT OF THE ABOVE MATRIX IS:"<<result;
getch();
}
void read(int b[5][5],int m) //FUNCTION FOR READING MATRIX
{
cout<<"
ENTER "<<m*m<<" ELEMENTS OF MATRIX(ROW-WISE):";
for(int i=0;i<m;i++)
for(int j=0;j<m;j++)
cin>>b[i][j];
}
void print(int b[5][5],int m)
{
clrscr(); //FUNCTION FOR PRINTING MATRIX
cout<<"
MATRIX IS :-
";
for(int i=0;i<m;i++)
{
cout<<"
";
for(int j=0;j<m;j++)
cout<<" "<<b[i][j];
}
}
int determinant(int b[5][5],int m) //FUNCTION TO CALCULATE
DETERMINANT
{
int i,j,sum = 0,c[5][5];
if(m==2)
{ //BASE CONDITION
sum = b[0][0]*b[1][1] - b[0][1]*b[1][0];
return sum;
}
for(int p=0;p<m;p++)
{
int h = 0,k = 0;
for(i=1;i<m;i++)
{
for( j=0;j<m;j++)
{
if(j==p)
continue;
c[h][k] = b[i][j];
k++;
if(k == m-1)
{
h++;
k = 0;
}
}
}
sum = sum + b[0][p]*pow(-1,p)*determinant(c,m-1);
}
return sum;
}
using the code written above we can check the det of the given matrix is -77871
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.