File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -37,6 +37,7 @@ public static void main(String[] args) {
3737 System .out .println ("2 * m2:\n " + m2 .scale (2 ));
3838 System .out .println ("m2 + m3:\n " + m2 .plus (m3 ));
3939 System .out .println ("m2 - m3:\n " + m2 .minus (m3 ));
40+ System .out .println ("m2 * m3: \n " +m2 .multiply (m3 ));
4041 }
4142
4243
@@ -157,6 +158,32 @@ public Matrix minus(Matrix other) throws RuntimeException {
157158
158159 return new Matrix (newData );
159160 }
161+
162+ /**
163+ * Multiplies this matrix with another matrix.
164+ *
165+ * @param other : Matrix to be multiplied with
166+ * @return product
167+ */
168+ public Matrix multiply (Matrix other ) throws RuntimeException {
169+
170+ int [][] newData = new int [this .data .length ][other .getColumns ()];
171+
172+ if (this .getColumns () !=other .getRows ())
173+ throw new RuntimeException ("The two matrices cannot be multiplied." );
174+ int sum ;
175+ for (int i = 0 ; i < this .getRows (); ++i )
176+ for (int j = 0 ; j < other .getColumns (); ++j ){
177+ sum = 0 ;
178+ for (int k =0 ;k <this .getColumns ();++k ){
179+ sum += this .data [i ][k ] * other .getElement (k , j );
180+ }
181+ newData [i ][j ] = sum ;
182+ }
183+
184+
185+ return new Matrix (newData );
186+ }
160187
161188 /**
162189 * Checks if the matrix passed is equal to this matrix
You can’t perform that action at this time.
0 commit comments