Advice in writing a function that raises a matrix to a certain power

Jul 28, 2013 at 3:18pm
Hello everyone,
I'm having trouble with my project. I have most of the code already written but am confused as how to make a new class where it takes my matrix and raises it to a certain power. I know I will need a for loop to make the matrix keep multiplying itself but am confused as to how to do this. If someone could help me out, that'd be great. I have posted the project below as well as the code I have already written.

Here is the project.
Revise class matrix from figure 8.9 by adding member function power. This member function should take an integer input parameter n and a matrix output parameter mToTheN. If the default object is a square matrix (same number of rows as columns), power should store in mToTheN the default matrix raised to the nth power. Raising a square matrix M to a power n is defined as the product of n copies of M.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;

const int MAX_ROWS = 6;
const int MAX_COLS = 6;

class Matrix		// This class was created to represent a matrix
{
public:
  Matrix() {}
  Matrix( int, int, int );
                           
  Matrix& operator*=( const Matrix& );
private:
  int rows;
  int cols;
  int mat[MAX_ROWS][MAX_COLS];
friend ostream& operator<< ( ostream&, const Matrix& );
friend istream& operator>> ( istream&, Matrix& );
};


// The main routine will input two identical matrices from a file designated by the user.

int main()
{
	int n;	// The variable that will be used to represent the power the matrix will be raised to
	int i;		// Variable used to evaluate matrix when raised to power of 1 
	Matrix m1;
	Matrix m2;
	string file1Name;

	cout << "Name of file containing first matrix => ";
	cin >> file1Name;
	ifstream infilOne( file1Name.c_str(), ios::in );
	infilOne >> m1;
	infilOne.close();

	ifstream infilTwo( file1Name.c_str(), ios::in );
	infilOne >> m2;
	infilOne.close();

	cout << " Enter the value of n that the matrix should be raised to " << endl;
	cin >> n;

	if ( n==1 )
		return m1;

	if (!infilOne.fail() && ! infilOne.fail()) 
	{
	cout << endl << "Matrix 1" << endl << endl << m1 << endl << endl;
	cout << "Matrix 2" << endl << endl << m2 << endl << endl;
		m1 *= m2;
		cout << "Matrix 1 x Matrix 2 = " << endl << endl << m1 << endl << endl;
		} 
		else 
		{
		cout << "Error in input" << endl;
		}
	}
	return 0;
}

// Multiplies m1 by m1 if the matrices are conformable.
// Otherwise, displays an error message and sets m1's size to 0 x 0

Matrix& Matrix :: operator*=(const Matrix& m2 ) // input
{
  int val, i, j, k;
  Matrix prod;
   
  if (cols != m2.rows) {
     cout << "Matrices are not conformable." << endl;
     prod.rows = 0;
     prod.cols = 0;
  } else {
     prod.rows = rows;
     prod.cols = m2.cols;
     for (i = 0; i < prod.rows; ++i)
        for (j = 0; j < prod.cols; ++j) {
           val = 0;
           for (k = 0; k < cols; ++k)
              val += mat[i][k] * m2.mat[k][j];
           prod.mat[i][j] = val;
        }
  }

  *this = prod;
  return *this;
}

// Prints out the contents of matrix m1

ostream& operator<< ( ostream& os, const Matrix& m )
{
  for (int i = 0; i < m.rows; ++i) {
     for (int j = 0; j < m.cols; ++j)
        cout << setw( 5 ) << m.mat[i][j];
     cout << endl;
  }
    return os;
}

istream& operator>> ( istream& is, Matrix& m )
{
  int i, j;

  is >> m.rows >> m.cols;
  if (is.fail()) {
     m.rows = 0;
     m.cols = 0;
  } else if (m.rows > MAX_ROWS || m.cols > MAX_COLS) {
     is.setstate( ios::failbit);
     m.rows = 0;
     m.cols = 0;
  } else {
     for (i = 0; i < m.rows; ++i)
        for (j = 0; j < m.cols; ++j)
           is >> m.mat[i][j];
     if (is.fail()) {
        m.rows = 0;
        m.cols = 0;
     }
  }

  return is;
}
Last edited on Jul 29, 2013 at 3:39pm
Jul 28, 2013 at 3:24pm
1
2
3
4
5
6
7
8
Matrix( int &rows, int &columns, int power)
{
     for(int a=0; a<columns; a++){
     for (int b=0; b<rows; b++){
                  pow(matrix[a][b],power);
             }
     }
}



This will make you a matrix raise to any power
Last edited on Jul 28, 2013 at 3:28pm
Jul 28, 2013 at 5:54pm
@eaglesfan

Your post is rather hard to read with all the unformatted code. Could you please go back and edit it to use code tags.

How to use code tags
http://www.cplusplus.com/articles/jEywvCM9/

But if your operator* is correctly defined, then raising the matrix to a power should work like any other type. So you could get it to work for ints and then convert the funtion to use matrices.

(Your matrix class does look rather incomplete at the moment?!)

Andy

PS @ Albo Coder

1. you're not storing the return from the pow function
2. I'm not sure that raising the elements individually to a given power is what eaglesfan is after
Last edited on Jul 28, 2013 at 5:55pm
Jul 28, 2013 at 8:56pm
1
2
3
4
5
6
7
8
9
void Matrix( int &rows, int &columns, int power)
{
     for(int a=0; a<columns; a++){
     for (int b=0; b<rows; b++){
                 cout << pow(matrix[a][b],power);
             }
       cout << "\n";
     }
}


This one prints every elements in x power
If that is what you want...
How a matrix mathematically rises in x power??

Jul 28, 2013 at 9:35pm
How a matrix mathematically rises in x power??

Using matrix multiplication.

Andy

For

Matrix

    1    2
    3    4


you get

Matrix ^ 0

    1   0
    0   1

Matrix ^ 1

    1   2
    3   4

Matrix ^ 2

    7   10
   15   22

Matrix ^ 3

   37   54
   81  118

Matrix ^ 4

  199  290
  435  634

Matrix ^ 5

 1069 1558
 2337 3406
Last edited on Jul 28, 2013 at 9:39pm
Jul 29, 2013 at 3:19pm
How do we get them mathematically?
What crap do we multiply?
Jul 29, 2013 at 3:42pm
Okay I edited the code and used code tags this time, thanks for showing me that. Maybe you can get a better look at it now andywestken.
Jul 29, 2013 at 4:01pm
You don't need new class. A function which works with your matrix class.

Matrix pow(Matrix m, unsigned int n);

And as I said before, this should work just like a function which raises an int to an (unsigned) int power.

But I can see issues with your code:
1. you're trying to read m2 from infilOne (after closing it!) rather than infilTwo
2. you're trying to return a matrix variable from main

(the second means your code won't even compile!)

The list of powers I posted above was created using your code after:
1. I got rid of m2 and its associated file
2. I got rid of the broken return
3. I added code which used your operator* to multiply the matrix (using a while loop), starting off with a unit matrix of the right size.
4. I also had to fix the constructors and add methods to set and get elements to I could set a matrix to the required values for it to be a unit matrix. Plus methods to get the size of the input matrix.

Andy

@ Albo Coder

See: Matrix multiplication
http://en.wikipedia.org/wiki/Matrix_multiplication
Last edited on Jul 29, 2013 at 4:08pm
Jul 30, 2013 at 12:13am
Okay great with your suggestions, I got it to compile. Thanks Andy.
Topic archived. No new replies allowed.