From 8fefa681f2ee39548bcd4ec0b060b907bdc96673 Mon Sep 17 00:00:00 2001 From: iliya <iliya.saroukha@hes-so.ch> Date: Fri, 29 Sep 2023 16:37:15 +0200 Subject: [PATCH] matrix --- serie1/Matrix.java | 56 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 serie1/Matrix.java diff --git a/serie1/Matrix.java b/serie1/Matrix.java new file mode 100644 index 0000000..82afa1f --- /dev/null +++ b/serie1/Matrix.java @@ -0,0 +1,56 @@ +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); + } +} -- GitLab