Skip to content
Snippets Groups Projects
Commit 8fefa681 authored by iliya's avatar iliya
Browse files

matrix

parent 74ea09e9
No related branches found
No related tags found
No related merge requests found
public class Matrix {
public static void printMatrix(int[][] mat) {
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
System.out.printf("%d ", mat[i][j]);
}
System.out.println();
}
}
public static int[][] mul(int[][] lhs, int[][] rhs) {
if (lhs[0].length != rhs.length) {
throw new RuntimeException("y axis of lhs doesn't match the x axis of rhs, multiplication cannot be done");
}
int[][] res = new int[lhs.length][rhs[0].length];
for (int i = 0; i < lhs.length; i++) {
for (int j = 0; j < rhs[i].length; j++) {
for (int k = 0; k < rhs.length; k++) {
res[i][j] += lhs[i][k] * rhs[k][j];
}
}
}
return res;
}
public int[][] add(int[][] lhs, int[][] rhs) {
if (lhs.length != rhs.length || lhs[0].length != rhs[0].length) {
throw new RuntimeException("y axis of lhs doesn't match the x axis of rhs, multiplication cannot be done");
}
int[][] res = new int[lhs.length][lhs[0].length];
for (int i = 0; i < res.length; i++) {
for (int j = 0; j < res[i].length; j++) {
res[i][j] = lhs[i][j] + rhs[i][j];
}
}
return res;
}
public static void main(String[] args) {
int[][] mat1 = new int[3][5];
int[][] mat2 = new int[5][4];
int res[][] = mul(mat1, mat2);
printMatrix(res);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment