Adjoint of Matrices in C++

The adjoint of a matrix is also called the adjugate of a matrix. It is defined as the transpose of the cofactor matrix of that particular matrix. For matrix A, the adjoint is denoted as adj (A).
For example
Find the adjoint of a 2×2 matrix
2×2 matrix is
A=[1 8 ]
[4 6 ]
Adjoint of matrix A is A=[6 −8 ]
[-4 1]

An adjoint of a matrix is generally a square matrix with the n × n. It is a transpose of the cofactor of the original matrix. The formula to find the adjoint of the matrix is done by using the cofactor and transpose of the matrix.

Code:

//ADJOINT of matrices :)

#include<iostream>
#include<math.h>
#include<conio.h>
using namespace std;
int main()
{
	int n;
	system("color b4 ");
	do
	{
	cout<<"\n\n\tEnter Size of Matrix : \n\n";
	cout<<"\t1-One x One "<<endl;
	cout<<"\t2-Two x Two"<<endl;
	cout<<"\t3-Three x Three "<<endl<<"\t";
	cin>>n;
	}
	while(n>4 || n<1) ;
	//system("CLS");
	//system("color F3");
	int mat[n][n],adj[n][n];
	cout<<"\n\n\tEnter Elements now \n";
	int i,j;
	//enter elements
	for(i=0;i<n;i++)
	{
		for(j=0;j<n;j++)
		{
			cout<<"\tElement ["<<i+1<<"]["<<j+1<<"] : ";cin>>mat[i][j];
		}
	}
	cout<<"\n\t";
	if(n==1)
	{
		adj[0][0]=mat[0][0];

	}
	//2x2 matrix determinent
	if(n==2)
	{
		//2X2 matrix determinent
		adj[0][0]=mat[1][1];
		adj[0][1]=-1*mat[0][1];
		adj[1][0]=-1*mat[1][0];
		adj[1][1]=mat[0][0];
	}
	if(n==3)
	{
		//3X3 matrix adjoint
		//cofactor 11
		adj[0][0]=pow(-1,1+1)*(mat[1][1]*mat[2][2]-mat[1][2]*mat[2][1]);
		//cofactor 12
		adj[0][1]=pow(-1,1+2)*(mat[1][0]*mat[2][2]-mat[1][2]*mat[2][0]);
		//cofactor 13
		adj[0][2]=pow(-1,1+3)*(mat[1][0]*mat[2][1]-mat[1][1]*mat[2][0]);
		//cofactor 21
		adj[1][0]=pow(-1,2+1)*(mat[0][1]*mat[2][2]-mat[0][2]*mat[2][1]);
		//cofactor 22
		adj[1][1]=pow(-1,2+2)*(mat[0][0]*mat[2][2]-mat[0][2]*mat[2][0]);
		//cofactor 23
		adj[1][2]=pow(-1,2+3)*(mat[0][0]*mat[2][1]-mat[0][1]*mat[2][0]);
		//cofactor 31
		adj[2][0]=pow(-1,3+1)*(mat[0][1]*mat[1][2]-mat[0][2]*mat[1][1]);
		//cofactor 32
		adj[2][1]=pow(-1,3+2)*(mat[0][0]*mat[1][2]-mat[0][2]*mat[1][0]);
		//cofactor 33
		adj[2][2]=pow(-1,3+3)*(mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0]);
	}
	//print matrix adjoint
	cout<<"\n\tADJOINT OF "<<n<<" x "<<n<<" MATRIX IS  \n\n";
	for(i=0;i<n;i++)
	{
		for(j=0;j<n;j++)
		{
			cout<<"\t"<<adj[j][i]<<"\t";
		}
		cout<<endl;
	}
	getch();
}

Output:

        Enter Size of Matrix :

        1-One x One
        2-Two x Two
        3-Three x Three
        2


        Enter Elements now
        Element [1][1] : 1
        Element [1][2] : 6
        Element [2][1] : 2
        Element [2][2] : 9


        ADJOINT OF 2 x 2 MATRIX IS

        9               -2
        -6              1

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *