You are on page 1of 2

//www.math.ucla.edu/~wittman/10a.1.10w/ccc/ch17/Code/matrix1.

cpp -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859
-1"></head><body style="">
<tt>
<pre> 1 #include &lt;cassert&gt;
2 #include &lt;iomanip&gt;
3
4 #include "matrix1.h"
5
6 Matrix::Matrix()
7 {
8 for (int i = 0; i &lt; ROWS; i++)
9 for (int j = 0; j &lt; COLUMNS; j++)
10 (*this)(i, j) = 0;
11 }
12
13 double&amp; Matrix::operator()(int i, int j)
14 {
15 assert(0 &lt;= i &amp;&amp; i &lt; ROWS &amp;&amp; 0 &lt;= j &amp;&amp;
j &lt; COLUMNS);
16 return elements[i * COLUMNS + j];
17 }
18
19 double Matrix::operator()(int i, int j) const
20 {
21 assert(0 &lt;= i &amp;&amp; i &lt; ROWS &amp;&amp; 0 &lt;= j &amp;&amp;
j &lt; 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&amp; 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&amp; Matrix::operator+=(const Matrix&amp; right)
58 {
59 for (int i = 0; i &lt; Matrix::ROWS; i++)
60 for (int j = 0; j &lt; Matrix::COLUMNS; j++)
61 (*this)(i, j) += right(i, j);
62 return *this;
63 }
64
65 Matrix operator+(const Matrix&amp; left, const Matrix&amp; right)
66 {
67 Matrix result = left;
68 result += right;
69 return result;
70 }
71
72 Matrix operator*(const Matrix&amp; left, const Matrix&amp; right)
73 {
74 Matrix result;
75 for (int i = 0; i &lt; Matrix::ROWS; i++)
76 for (int j = 0; j &lt; Matrix::COLUMNS; j++)
77 for (int k = 0; k &lt; Matrix::COLUMNS; k++)
78 result(i, j) += left(i, k) * right(k, j);
79 return result;
80 }
81
82 Matrix operator*(const Matrix&amp; left, double right)
83 {
84 Matrix result;
85 for (int i = 0; i &lt; Matrix::ROWS; i++)
86 for (int j = 0; j &lt; Matrix::COLUMNS; j++)
87 result(i, j) = left(i, j) * right;
88 return result;
89 }
90
91 Matrix operator*(double left, const Matrix&amp; right)
92 {
93 return right * left;
94 }
95
96 ostream&amp; operator&lt;&lt;(ostream&amp; left, const Matrix&amp; right)
97 {
98 const int WIDTH = 10;
99 for (int i = 0; i &lt; Matrix::ROWS; i++)
100 {
101 for (int j = 0; j &lt; Matrix::COLUMNS; j++)
102 left &lt;&lt; setw(WIDTH) &lt;&lt; right(i, j);
103 left &lt;&lt; "\n";
104 }
105 return left;
106 }</pre>
</tt>
</body></html>

You might also like