Professional Documents
Culture Documents
Matrix 1
Matrix 1
cpp -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859
-1"></head><body style="">
<tt>
<pre> 1 #include <cassert>
2 #include <iomanip>
3
4 #include "matrix1.h"
5
6 Matrix::Matrix()
7 {
8 for (int i = 0; i < ROWS; i++)
9 for (int j = 0; j < COLUMNS; j++)
10 (*this)(i, j) = 0;
11 }
12
13 double& Matrix::operator()(int i, int j)
14 {
15 assert(0 <= i && i < ROWS && 0 <= j &&
j < COLUMNS);
16 return elements[i * COLUMNS + j];
17 }
18
19 double Matrix::operator()(int i, int j) const
20 {
21 assert(0 <= i && i < ROWS && 0 <= j &&
j < COLUMNS);
22 return elements[i * COLUMNS + j];
23 }
24
25 MatrixRow Matrix::operator[](int i)
26 {
27 return MatrixRow(this, i);
28 }
29
30 ConstMatrixRow Matrix::operator[](int i) const
31 {
32 return ConstMatrixRow(this, i);
33 }
34
35 MatrixRow::MatrixRow(Matrix* m, int s)
36 {
37 mat = m;
38 i = s;
39 }
40
41 double& MatrixRow::operator[](int j)
42 {
43 return (*mat)(i,j);
44 }
45
46 ConstMatrixRow::ConstMatrixRow(const Matrix* m, int s)
47 {
48 mat = m;
49 i = s;
50 }
51
52 double ConstMatrixRow::operator[](int j) const
53 {
54 return (*mat)(i, j);
55 }
56
57 Matrix& Matrix::operator+=(const Matrix& right)
58 {
59 for (int i = 0; i < Matrix::ROWS; i++)
60 for (int j = 0; j < Matrix::COLUMNS; j++)
61 (*this)(i, j) += right(i, j);
62 return *this;
63 }
64
65 Matrix operator+(const Matrix& left, const Matrix& right)
66 {
67 Matrix result = left;
68 result += right;
69 return result;
70 }
71
72 Matrix operator*(const Matrix& left, const Matrix& right)
73 {
74 Matrix result;
75 for (int i = 0; i < Matrix::ROWS; i++)
76 for (int j = 0; j < Matrix::COLUMNS; j++)
77 for (int k = 0; k < Matrix::COLUMNS; k++)
78 result(i, j) += left(i, k) * right(k, j);
79 return result;
80 }
81
82 Matrix operator*(const Matrix& left, double right)
83 {
84 Matrix result;
85 for (int i = 0; i < Matrix::ROWS; i++)
86 for (int j = 0; j < Matrix::COLUMNS; j++)
87 result(i, j) = left(i, j) * right;
88 return result;
89 }
90
91 Matrix operator*(double left, const Matrix& right)
92 {
93 return right * left;
94 }
95
96 ostream& operator<<(ostream& left, const Matrix& right)
97 {
98 const int WIDTH = 10;
99 for (int i = 0; i < Matrix::ROWS; i++)
100 {
101 for (int j = 0; j < Matrix::COLUMNS; j++)
102 left << setw(WIDTH) << right(i, j);
103 left << "\n";
104 }
105 return left;
106 }</pre>
</tt>
</body></html>