Search from Cycling Blog

Computing Matrices

Language: C++

Author: Aamir Mustafa

 

Introduction:

In this article, two simple matrices will be computed. We will take values for two matrices and then we will add and subtract them.

 

First of all we will write a Matrix class. This class contains one member variable called matrix, it is two dimensional and we declare it in private part of the class.

After that we declare two members functions in the public part of the class so we can access these member functions out of the class. These are get(), display() and Compute() functions.

get() function will get values through loops.

display() will show values of matrices through  loops.

Compute() will compute the matrices for subtraction and addition.

After that we write two operators and here we overload them which is called operator overloading.

First of all we will write the name of Class which is Matrix, after that the operator key word and then + or – for adding and subtracting matrices. After that we write const keyword and then the name of class and variable.

Matrix operator + (const Matrix& m)

 

After that our complete class looks like.

//including necessary libraries

#include<iostream>

#include<conio.h>

//declaring Matrix class

class Matrix

{

private:

int matrix[2][2]; //members variables

public:

void get()              //member function get() which gets values for matrices

{

for(int i=0;i<2;i++)

for(int j=0;j<2;j++)

cin>>matrix[i][j];

}

void Display()  //this member function displays computed values of two matrices.

{

for(int i=0;i<2;i++)

for(int j=0;j<2;j++)

cout<<matrix[i][j]<<"\t";

}

Matrix operator-(const Matrix& m)//operator overloading

{

Matrix mn;              //creating an object of class Matrix

for(int i=0;i<2;i++)

for(int j=0;j<2;j++)

mn.matrix[i][j]=matrix[i][j]-m.matrix[i][j];

return mn;

}

Matrix operator + (const Matrix& m)//operator overloading

{

Matrix mn;              //creating an object of class Matrix

for(int i=0;i<2;i++)

for(int j=0;j<2;j++)

mn.matrix[i][j]=matrix[i][j]+m.matrix[i][j];

return mn;

}

 

void Compute()          //member function for computing matrices.

{

Matrix Mat1,Mat2,Mat3;  //creating three objects

cout<<"\nEnter elements into the first matrix:\n";

Mat1.get();                   //getting values of first matrix

cout<<"\nEnter elements into the second matrix:\n";

Mat2.get();                   //getting values of second matrix

Mat3=Mat1+Mat2;               //adding two matrices and saving them in mat3

cout<<"\n\nThe Matrix addition is:",Mat3.Display(),"\n";

Mat3=Mat1-Mat2;

cout<<"\n\nThe Matrix subtraction is:",Mat3.Display(),"\n";

}

};

After this we write our main function. Here we will create a matrix object m and then access Compute function through this object m.

main()

{

Matrix m;    //creating an object

m.Compute();

getche();

}

 

Comments are needed.

 

0 comments: