Skip to content

Commit 7e5b82c

Browse files
authored
Merge pull request TheAlgorithms#319 from NISHITA97/Branch2
Updated Matrix.java
2 parents df6838e + 86d545b commit 7e5b82c

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Data Structures/Matrix/Matrix.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff 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

0 commit comments

Comments
 (0)