Calculate the Determinant of A Square Matrix

This is a code that I wrote weeks ago, mainly to calculate the determinant of a squae matrix.

It’s written in c++. Enjoy it!

 #include <iostream>
using namespace std;
template<typename T>
class Matrix{
	T **m;
	int n;
	void rot90(){
		T ** tmp=new T*[n];
		for(int i=0;i<n;i++){
			tmp[i]=new T[n];
			for(int j=0;j<n;j++){
				tmp[i][j]=m[i][j];
			}
		}
		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				m[i][j]=tmp[n-1-j][i];
			}
		}
	}
	Matrix<t> M(int i,int j){//get the matrix corresponds with specific minor Mij
		Matrix<t> TMP(n-1);
		for(int a=0;a<n-1;a++){
			for(int b=0;b<n-1;b++){
				int c=0,d=0;
				if(a<i) c=a;
				else c=a+1;
				if(b<j) d=b;
				else d=b+1;
				TMP.m[a][b]=m[c][d];
			}
		}
		return TMP;
	}
	T C(int i,int j){//get cofactor Cij
		if((i+j)%2==0) return M(i,j).Det();
		else return -1*M(i,j).Det();
	}
	T A(int i,int j){
		return m[i][j]*C(i,j);
	}
public :

	Matrix(int para){
		n=para;
		m=new T*[n];
		for(int i=0;i<n;i++){
			m[i]=new T[n];
			for(int j=0;j<n;j++) m[i][j]=0;
		}
	}
	Matrix(){
		int itmp=0;
		do{
			cout<<"Please input the square matrix's  n, and n has to be larger than 1"<<endl;
			cin>>itmp;
		}
		while(itmp<2);
		n=itmp;
		m=new T*[n];
		for(int i=0;i<n;i++){
			m[i]=new T[n];
			for(int j=0;j<n;j++) m[i][j]=0;
		}
	}
	void Input(){
		cout<<"Please initialize the matrix"<<endl;
		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++) cin>>m[i][j];
		}
		cout<<"Initialization done"<<endl;
	}
	void Display(){
		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				cout<<m[i][j];
				if(j!=n-1) cout<<" ";
			}
			cout<<endl;
		}
	}
	void Display(int w){
		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				cout<<setw(w)<<m[i][j];
			}
			cout<<endl;
		}
	}
	void Display(int i,int j){
		cout<<m[i][j]<<endl;
	}
	void Rotation(int times=1){
		for(;times>3;times-=4){}
		for(;times<0;times+=4){}
		if(times!=0){
			if(times==1) rot90();
			else{
				rot90();
				Rotation(times-1);
			}
		}
	}
	T Det(){
		if(n==2) return m[0][0]*m[1][1]-m[0][1]*m[1][0];
		else{
			T sum=0;
			for(int i=0;i<n;i++) sum+=A(0,i);
			return sum;
		}
	}
}; 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.