Thursday, October 27, 2016

Matrix Operations Using Objects

Tags

Write a Class Template by the name matrix and perform the following operations:
1. Sum of 2 Matrices
2. Product of 2 Matrices
3. Sum of each row of matrix and display them
4. Sum of each column of matrix and display them


Solution:
#include<iostream>
using namespace std;
template<class T>
class matrix
{
T a[10][10];
public: int m,n;
matrix()
{
cout<<"Enter The Order of Matrix\n";
cin>>m>>n;
cout<<"Enter The Elements of Matrix\n";
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
cin>>a[i][j];
}
matrix(int x,int y)
{  m=x;n=y;
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
a[i][j]=0;
}
matrix operator +(matrix b)
{
matrix<T>c(b.m,b.n);
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
c.a[i][j]=a[i][j]+b.a[i][j];
return c;
}
matrix operator *(matrix b)
{
matrix<T>c(m,b.n);
if(n!=b.m)
{
cout<<"Multiplication Not Possible\n";
}
else
{for(int i=0;i<m;i++)
for(int j=0;j<b.n;j++)
{c.a[i][j]=0;
for(int k=0;k<n;k++)
c.a[i][j]+=a[i][k]*b.a[k][j];}

    return c;
}
}
void sumr()
{    T sum=0.0;
for(int i=0;i<m;i++)
{ sum=0.0;
for(int j=0;j<n;j++)
{
sum+=a[i][j];
}
cout<<"Sum of"<<i+1<<" row is "<<sum<<"\n";
}
}
void sumc()
{    T sum=0.0;
for(int i=0;i<n;i++)
{ sum=0.0;
for(int j=0;j<m;j++)
{
sum+=a[j][i];
}
cout<<"Sum of"<<i+1<<"column is "<<sum<<"\n";
}
}
void display()
{
cout<<"Elements Are\n";
for(int i=0;i<m;i++)
{for(int j=0;j<n;j++)
{cout<<a[i][j]<<"\t";}
cout<<"\n";}
}

};
main()
{
matrix<int>a,b,c(a.m,b.n);
c=a+b;
cout<<"\nSum is\n";
c.display();
cout<<"\nProduct is\n";
c=a*b;
c.display();
cout<<"\nSum of Rows of A\n";
a.sumr();
cout<<"\nSum of Columns Of A\n";
a.sumc();

}