-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix.cpp
More file actions
104 lines (102 loc) · 2.56 KB
/
matrix.cpp
File metadata and controls
104 lines (102 loc) · 2.56 KB
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
#include "matrix.h"
#include <iomanip>
Matrix::Matrix()
{
rows = 0;
columns = 0;
};
/* Constructors */
Matrix::Matrix(int number_of_rows, int number_of_columns)
{
rows = number_of_rows;
columns = number_of_columns;
for (int r = 0; r < rows; ++r)
{
std::vector<double> row (columns, 0);
array.push_back(row);
}
}
Matrix::Matrix(int number_of_rows, int number_of_columns, std::vector< std::vector<double> > elements)
{
rows = number_of_rows;
columns = number_of_columns;
if (elements.size() != number_of_rows)
{
std::cout << "Warning: number of rows does not match elements." << std::endl;
}
if (rows > 0 && elements[0].size() != number_of_columns)
{
std::cout << "Warning: number of columns does not match elements." << std::endl;
}
array = elements;
}
/* Methods */
void Matrix::print()
{
std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout << "[" << std::endl;
for (int r = 0; r < rows; ++r)
{
std::cout << "[";
for (int c = 0; c < columns; ++c)
{
std::cout << array[r][c];
if (c != columns - 1)
{
std::cout << ", ";
}
}
std::cout << "]";
if (r != rows - 1)
{
std::cout << "," << std::endl;
}
}
std::cout << std::endl << "]" << std::endl;
}
Matrix Matrix::transpose()
{
std::vector< std::vector<double> > result_array;
for (int r = 0; r < columns; ++r)
{
std::vector<double> row;
for (int c = 0; c < rows; ++c)
{
row.push_back(array[c][r]);
}
result_array.push_back(row);
}
return Matrix(columns, rows, result_array);
}
Matrix Matrix::getRow(int number_of_row) const
{
if (number_of_row < 0 || number_of_row >= rows)
{
std::cout << "Error: row number is out of range" << std::endl;
return Matrix();
}
std::vector< std::vector<double> > row;
row.push_back(array[number_of_row]);
return Matrix(1, columns, row);
}
Matrix operator* (const Matrix& a, const Matrix& b)
{
if (a.columns != b.rows)
{
std::cout << "Error: dimensions do not match" << std::endl;
return Matrix();
}
Matrix result = Matrix(a.rows, b.columns);
for (int r = 0; r < a.rows; r++)
{
for (int c = 0; c < b.columns; ++c)
{
for (int k = 0; k < a.columns; ++k)
{
result.array[r][c] += a.array[r][k]*b.array[k][c];
}
}
}
return result;
}