Matrix Multiplication

Hey again (C++ Noobie Day 3),

I spend most of my early years programming in Java, recently I've been using MATLAB for a lot of uni stuff (Engineering). Anyway, after tackling matrix multiplication in C++ today (I'm working on a 3D game lol going to be an uphill battle) I now fully appreciate how easy MATLAB makes things haha

After encountering a pile of problems with passing 2D arrays of unknown width to functions etc I've finally reached a solution. I was wondering if anyone could comment on what I've done here - It seems like a lot of work... maybe I'm making things hard for myself? Looking for stuff like bad practice etc.

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

#include "matrixMultiply.h"
#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{

    //Working On 2D Array
    int rows1 = 3;
    int columns1 = 1;
    float **matrixOne = (float**)malloc(rows1 * sizeof(*matrixOne));
	for(int i = 0; i < rows1; i++)
	{
		matrixOne[i] = (float*)malloc(columns1 * sizeof(float));
	}

    matrixOne[0][0] = 1;
    matrixOne[1][0] = -1;
    matrixOne[2][0] = 1;

    int rows2 = 1;
    int columns2 = 3;
    float **matrixTwo = (float**)malloc(rows2 * sizeof(*matrixTwo));
	for(int i = 0; i < rows2; i++)
	{
		matrixTwo[i] = (float*)malloc(columns2 * sizeof(float));
	}


    matrixTwo[0][0] = 1;
    matrixTwo[0][1] = -1;
    matrixTwo[0][2] = 1;


    float **result;
    result = (float**)malloc(rows1 * sizeof(*result));
	for(int i = 0; i < rows1; i++)
	{
		result[i] = (float*)malloc(columns2 * sizeof(float));
	}


    matrixMultiply(3,1,matrixOne,1,3,matrixTwo, result);

    return 0;

}

void matrixMultiply(int rows1, int cols1, float **mat1, int rows2, int cols2, float **mat2, float **result)
{

    if( cols1 != rows2 ){

        cout << "Can't Multiply These Matricies!";

    }
    else{

        float tempResult;

        for (int i=0;i<rows1;i++)
        {

            for(int j=0;j<cols2;j++)
            {

                tempResult = 0;

                for(int k=0;k<rows2;k++)
                {
                  
                    tempResult += mat1[i][k]*mat2[k][j];

                }

                result[i][j] = tempResult;

            }


        }

    }


}



Any help would be greatly appreciated,

Nick :)

Last edited on
I would suggest that instead of using multi-dimensional arrays, you just use a single dimensional array, and use an offset to access stuff:

1
2
3
int* array[height*width];

array[(y_pos*width)+x_pos]; //or something similar 


That way you only have to free one array and you don't have to deal with pointers to pointers, etc.

Why not create a Matrix object ? Depending on the size of your project (which can get quite big for a 3D game), object oriented design might be a life-saver in the longrun.

Here's my implementation for a Matrix class with the most basic operations defined, note [] returns a row in the matrix.

note 2: There might be some dutch in the code, like in the error throws. I think these things explain themself, if not, just ask a translation and I will provide

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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
#include "Matrix.h"
#include <iostream>
using std::cout;


Matrix::Matrix(int rows, int cols) throw (CInvalidArgumentException)
{
	if(rows == 0 && cols == 0)
	{
		CInvalidArgumentException ex("0x0 matrix kan niet aangemaakt worden");
		throw (ex);
	}

	if(rows < 0 || cols < 0)
	{
		CInvalidArgumentException ex2("Een matrix kan geen negatieve dimensie-eenheid hebben");
		throw(ex2);
	}
		
	allocate(rows, cols);
}

void Matrix::allocate(int rows, int cols)
{
	m_rows = rows;
	m_cols = cols;
	
	m_pElementen = new double*[rows];
	
	for(int i=0; i<rows; i++)
	{
		m_pElementen[i] = new double[cols];
	}
}

void Matrix::toon() const
{
	for(int i=0; i<m_rows; i++)
	{
		cout<<"[";
		for(int j=0; j<m_cols; j++)
		{
			cout<<m_pElementen[i][j]<< " ";
		}
		cout<<"]\n";
	}
}

double Matrix::getElement(int row, int col) const throw (CInvalidArgumentException)
{
	if(row >= m_rows || col >= m_cols)
	{
		CInvalidArgumentException ex("row or column out of range");
		throw (ex);
	}
	return m_pElementen[row][col];
}

Matrix::Matrix(const Matrix & m)
{
	cout<<"\ncopy constructor\n";
	
	allocate(m.getRows(), m.getCols());
	for(int i=0; i<m_rows; i++)
	{
		for(int j=0; j<m_cols; j++)
		{
			m_pElementen[i][j] = m.getElement(i, j);
		}
	}
}

void Matrix::setElement(int row, int col, double value) throw(CInvalidArgumentException)
{
	if(row >= m_rows || col >= m_cols)
	{
		CInvalidArgumentException ex("row or column out of range");
		throw (ex);
	}
	m_pElementen[row][col] = value;
}

Matrix & Matrix::operator +=(const Matrix &m) throw(CInvalidArgumentException)
{
	if(this->getRows() != m.getRows() || this->getCols() != m.getCols())
	{
		CInvalidArgumentException ex("dimensies komen niet overeen om operator += uit te voeren");
		throw (ex);
	}
	for(int i=0; i<m_rows; i++)
	{
		for(int j=0; j<m_cols; j++)
		{
			m_pElementen[i][j] += m.getElement(i, j);
		}
	}
	return *this;
}

Matrix & Matrix::operator -=(const Matrix &m) throw(CInvalidArgumentException)
{
	if(this->getRows() != m.getRows() || this->getCols() != m.getCols())
	{
		CInvalidArgumentException ex("dimensies komen niet overeen om operator -= uit te voeren");
		throw (ex);
	}
	for(int i=0; i<m_rows; i++)
	{
		for(int j=0; j<m_cols; j++)
		{
			m_pElementen[i][j] -= m.getElement(i, j);
		}
	}
	return *this;
}

Matrix & Matrix::operator =(const Matrix &m)
{
	return Matrix(m);
}

Matrix Matrix::operator +(const Matrix & m) throw(CInvalidArgumentException)
{
	if(this->getRows() != m.getRows() || this->getCols() != m.getCols())
	{
		CInvalidArgumentException ex("dimensies komen niet overeen om operator + uit te voeren");
		throw (ex);
	}
	Matrix hulp = m;
	hulp += *this;
	return hulp;
}

Matrix Matrix::operator -(const Matrix & m) throw(CInvalidArgumentException)
{
	if(this->getRows() != m.getRows() || this->getCols() != m.getCols())
	{
		CInvalidArgumentException ex("dimensies komen niet overeen om operator - uit te voeren");
		throw (ex);
	}
	Matrix hulp = m;
	hulp -= *this;
	return hulp;
}

bool Matrix::operator ==(const Matrix &m)
{
	bool isEqual = true;
	for(int i=0; i<m_rows && isEqual; i++)
	{
		for(int j=0; j<m_cols && isEqual; j++)
		{
			isEqual = m_pElementen[i][j] == m.getElement(i, j);
		}
	}
	return isEqual;
}

bool Matrix::operator != (const Matrix &m)
{
	return !(*this == m);
}

Matrix Matrix::operator- (void)
{
	for(int i=0; i<m_rows; i++)
	{
		for(int j=0; j<m_cols; j++)
		{
			m_pElementen[i][j] = 0 - m_pElementen[i][j];
		}
	}
	return *this;
}



double Matrix::kruisproduct(int i, int j, Matrix m1, const Matrix & m2)
{
	double result = 0.0;
	for(int t=0; t<m1.getRows(); t++)
	{
		double elem1 = m1.m_pElementen[i][t];
		double elem2 = m2.getElement(t, j);
		result += elem1 * elem2;
	}
	
	return result;
}


Matrix & Matrix::operator*= (const Matrix & m) throw(CInvalidArgumentException)
{
	if(this->getCols() != m.getRows() || this->getRows() != m.getCols())
	{
		CInvalidArgumentException ex("dimensies komen niet overeen om operator *= uit te voeren");
		throw (ex);
	}
	Matrix product(m_rows, m.getCols());
	Matrix hulp(*this);
	cout<<"hulp:\n";
	hulp.toon();
	cout<<"m param:\n";
	m.toon();

	this->allocate(m_rows, m.getCols());
	
	for(int i=0; i<product.getRows(); i++)
	{
		for(int j=0; j<product.getCols(); j++)
		{
			this->setElement(i, j, kruisproduct(i, j, hulp, m));
		}
	}
	
	return *this;
}

Matrix Matrix::operator* (const Matrix & m) throw(CInvalidArgumentException)
{
	if(this->getCols() != m.getRows() || this->getRows() != m.getCols())
	{
		CInvalidArgumentException ex("dimensies komen niet overeen om operator * uit te voeren");
		throw(ex);
	}
	Matrix hulp(*this);
	hulp *= m;
	return hulp;
}

Matrix Matrix::operator [] (int index)
{
	Matrix m(1, this->getCols());
	for(int i=0; i<m_cols; i++)
		m.setElement(0, i, getElement(index, i));
	return m;
}

Last edited on
I agree about making an object; that is the entire point of OOP. However, providing the entire solution doesn't help the OP learn much.
Haha thanks to all that replied! The offset idea is genius lol can't believe that never crossed my mind. And that class you've written joe is amazing!!! I'm going to try write a Matrix class.

Thanks for everyone's help!

Nick
Last edited on
Zhuge: These are the most basic things in OO design in C++ combined in one class. I doubht NickPaul will use this class and won't start with the basics step by step if he still needs to learn OOP. This class can then be used as a usable example for his project.

If he on the other hand allready is familiar with OOP, this just saved him some typing :-)
Haha luckily for me Java was object orientated, however since I'm trying to learn C++ as quickly as possible (mainly pointers and some of the syntax) I will we writing the class myself lol probably won't be as comprehensive as yours at the start, but as I need more functionality I can build mine up to yours lol

Thanks again,

Nick
Well, this was a task for school and it has a few extensions beside the code I provided.
Think about inheritance, I bet you can think of some classes which can inherit (extend, yes I know a bit of java :-)) from the Matrix class.
Topic archived. No new replies allowed.