class matrix {
public static void main(String[] args) {
int[][] matrix1 = {{2,1},{1,3},{2,3},{4,2}};
int[][] matrix2 = {{1,3,2,1}};
int[][] matrix3 = {{-2,1},{-3,3},{2,-3},{14,2}};
addMatrices(matrix1, matrix3);
subtractMatrices(matrix3, matrix1);
multiplyMatrices(matrix1, matrix2);
}
public static void addMatrices(int[][] matrix1, int[][] matrix2) {
int[][] resultmatrix = new int[matrix1.length][matrix1[0].length];
try {
for (int y = 0; y < matrix1[0].length; y++) {
for (int x = 0; x < matrix1.length; x++) {
resultmatrix[x][y] =
matrix1[x][y] + matrix2[x][y];
}
}
printComment("A", "B", "+", matrix1, matrix2, resultmatrix);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Matrix dimensions don't match");
}
}
public static void subtractMatrices(int[][] matrix1, int[][] matrix2) {
int[][] resultmatrix = new int[matrix1.length][matrix1[0].length];
try {
for (int y = 0; y < matrix1[0].length; y++) {
for (int x = 0; x < matrix1.length; x++) {
resultmatrix[x][y] =
matrix1[x][y] - matrix2[x][y];
}
}
printComment("A", "B", "-", matrix1, matrix2, resultmatrix);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Matrix dimensions don't match");
}
}
public static void multiplyMatrices(int[][] matrix1, int[][] matrix2) {
int[][] resultmatrix = new int[matrix2.length][matrix1[0].length];
try {
for (int x = 0; x < resultmatrix.length; x++) {
for (int y = 0; y < resultmatrix[0].length; y++) {
for (int leftmatrix = 0; leftmatrix < matrix2[0].length; leftmatrix++) {
resultmatrix[x][y] += matrix1[leftmatrix][y] * matrix2[x][leftmatrix];
}
}
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Matrix dimensions don't match");
}
printComment("A", "B", "*", matrix1, matrix2, resultmatrix);
}
public static void printMatrix(int[][] matrix) {
for (int y = 0; y < matrix[0].length; y++) {
for (int x = 0; x < matrix.length; x++) {
System.out.print("[" + matrix[x][y] + "]");
}
System.out.println();
}
}
public static void printComment(String namefirst, String namesecond, String operation,
int[][] first, int[][] second, int[][] result) {
print(namefirst + "[" + first[0].length + "x" + first.length + "] " + ":");
printMatrix(first);
print("\n" + namesecond + "[" + second[0].length + "x" + second.length + "] " + ":");
printMatrix(second);
print("\n" + namefirst + "[" + first[0].length + "x" + first.length + "]" + " " + operation + " "
+ namesecond + "[" + second[0].length + "x" + second.length + "]"
+ " = C" + "[" + result[0].length + "x" + result.length + "] ");
printMatrix(result);
print("\n\n");
}
public static void print(String output) {
System.out.println(output);
}
}