Program to perform operations like addition, multiplicaton, etc. on matrix(Source Code)
// Program Ch02pr03
// Program to perform operations like addition, multiplicaton, etc. on matrix
#include
#include
using namespace std;
const int MAX = 3 ;
class matrix
{
private :
int **mat ;
int sz1, sz2;
public :
matrix( int siz1, int siz2) ;
void create( ) ;
void display( ) ;
void matadd ( matrix &m1, matrix &m2 ) ;
void matmul ( matrix &m1, matrix &m2 ) ;
void transpose ( matrix &m1 ) ;
} ;
// initializes the matrix mat with 0
matrix :: matrix(int siz1,int siz2 )
{
sz1=siz1;
sz2=siz2;
}
// creates matrix mat
void matrix :: create( )
{
int n ;
const int siz2=sz2;
mat = new int[sz1][MAX];
for ( int i = 0 ; i < sz1; i++ )
{
for ( int j = 0 ; j < sz2; j++ )
{
cout << "\nEnter the element : " ;
cin >> n ;
mat[i][j] = n ;
}
}
}
// displays the contents of matrix
void matrix :: display( )
{
for ( int i = 0 ; i < sz1 ; i++ )
{
for ( int j = 0 ; j < sz2 ; j++ )
cout << mat[i][j] << " " ;
cout << endl ;
}
}
// adds two matrices m1 and m2
void matrix :: matadd ( matrix &m1, matrix &m2 )
{
for ( int i = 0 ; i < m1.sz1 ; i++ )
{
for ( int j = 0 ; j < m1.sz2 ; j++ )
mat[i][j] = m1.mat[i][j] + m2.mat[i][j] ;
}
}
// multiplies two matrices m1 and m2
void matrix :: matmul ( matrix &m1, matrix &m2 )
{
for ( int k = 0 ; k < m1.sz1 ; k++ )
{
for ( int i = 0 ; i < m2.sz2 ; i++ )
{
for ( int j = 0 ; j < m1.sz2 ; j++ )
mat[k][i] += m1.mat[k][j] * m2.mat[j][i] ;
}
}
}
// obtains transpose of matrix m1
void matrix :: transpose ( matrix &m1 )
{
for ( int i = 0 ; i < sz1 ; i++ )
{
for ( int j = 0 ; j < sz2 ; j++ )
mat[i][j] = m1.mat[j][i] ;
}
}
int main( )
{
matrix mat1(MAX, MAX) , mat2(MAX, MAX);
cout << "\nEnter elements for first array: \n" ;
mat1.create( ) ;
cout << "\nEnter elements for second array: \n" ;
mat2.create( ) ;
cout << "\nFirst Array: \n" ;
mat1.display( ) ;
cout << "\nSecond Array:\n" ;
mat2.display( ) ;
matrix mat3 (MAX, MAX);
mat3.matadd ( mat1, mat2 ) ;
cout << "\nAfter Addition: \n" ;
mat3.display( ) ;
matrix mat4(MAX,MAX) ;
mat4.matmul ( mat1, mat2 ) ;
cout << "\nAfter Multiplication: \n" ;
mat4.display( ) ;
matrix mat5(MAX, MAX) ;
mat5.transpose ( mat1 ) ;
cout << "\nTranspose of first matrix: \n" ;
mat5.display( ) ;
getch();
}
Thursday, August 7, 2008
Program to perform operations like addition, multiplicaton, etc. on matrix
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment