All pastes #364484 Raw Edit

Stuff

public text v1 · immutable
#364484 ·published 2007-02-20 05:28 UTC
rendered paste body
matrix.h

#ifndef H_MATRIX
#define H_MATRIX


#include <iostream>
#include <vector>

using namespace std;

typedef vector<vector<int> > Matrix;

istream& operator>> (istream& input, Matrix& m);
ostream& operator<< (ostream& output, const Matrix& m);
Matrix operator+(const Matrix& m1,const Matrix& m2);
Matrix operator-(const Matrix& m1,const Matrix& m2);
Matrix operator*(const Matrix& m1,const Matrix& m2);
ostream& operator/(const Matrix& m1,const Matrix& m2);

#endif

#include "matrix.h"


Matrix operator+(const Matrix& m1,const Matrix& m2)
{
   if( (m1.size() == m2.size()) && (m1[0].size() == m2[0].size()) )
	{
		Matrix sum(m1.size(),m1[0].size());
		for (int i=0 ; i < m1.size() ; i++)
   		for (int j=0; j < m1[0].size() ; j++)
      		sum[i][j] = m1[i][j] + m2[i][j];
		return sum;
	}
	else
	{
		Matrix sum(1,1);
		return sum;
	}
}

Matrix operator-(const Matrix& m1,const Matrix& m2)
{
   if( (m1.size() == m2.size()) && (m1[0].size() == m2[0].size()) )
	{
		Matrix diff(m1.size(),m1[0].size());
		for (int i=0 ; i < m1.size() ; i++)
   		for (int j=0; j < m1[0].size() ; j++)
      		diff[i][j] = m1[i][j] - m2[i][j];
		return diff;
	}
	else
	{
		Matrix diff(1,1);
		return diff;
	}
}

Matrix operator*(const Matrix& m1,const Matrix& m2)
{
	if ( m1[0].size() == m2.size() )
	{
		Matrix product( m1.size(),m2[0].size() );
		for (int i = 0 ; i < product.size() ; i++)
		{	
			for ( int j = 0 ; j < product[0].size() ; j++)
			{	
				int sum=0;
				//make sure the multiplication takes place right
				//or else we'll get seg faults for matrices that
				//aren't square.
				if( product.size() < product[0].size())
					for ( int n = 0 ; n < product.size() ; n++)
						product[i][j] += m1[i][n] * m2[n][j];
				else
					for( int n = 0 ; n < product[0].size() ; n++)
						product[i][j] += m1[i][n] * m2[n][j];
			}
		}				
		return product;
	}
	else
	{
		cout << "cannot multiply these matrices, dimension mismatch\n";
		Matrix product(1,1);
		return product;
	}
}

ostream& operator/(const Matrix& m1,const Matrix& m2)
{
	ostream *p;
	 &p << "This operation is not defined for this data type\n";
	return p;
}

istream& operator>> (istream& input, Matrix& m)
{
	int rows, cols;
	cout << "Enter number of rows: ";
	cin >> rows;
	cout << "Enter number of columns: ";
	cin >> cols;

	//make a new vector to hold the input
	Matrix v(rows,cols);

	cout << v.size() << endl;
	cout << v[0].size() << endl;
	for ( int i = 0 ; i < rows; i++ )
		for( int j = 0 ; j < cols ; j++)
		{
			cout << "Enter the " << i+1 <<"," << j+1 << " element: ";
			input >> v[i][j];
		}

	//copy the input vector over
	m=v;

	return input;
}

ostream& operator<< (ostream& output, const Matrix& m)
{
	for ( int i = 0 ; i < m.size() ; i++ )
		for ( int j = 0 ; j < m[0].size() ; j++ )
		{
			output << m[i][j] << " ";
			if ( j == ( m[0].size() - 1 ) ) output << endl;
		}
	return output;
}