Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MatrixAddSubtract {
- public static void main(String[] args) {
- int[][] matrixA = new int[][]{{3,6,10,-1,4}, {6, 10, 5, 3, 1}, {4,4,10,40,-10}};
- int[][] matrixB = new int[][]{{1,-5, 0, 0, 0}, {2, 0, -14, 3, 2}, {3,3,10,100,-30}};
- System.out.println("\n\nMatrix A:");
- printMatrix(matrixA);
- System.out.println("\n\nMatrix B:");
- printMatrix(matrixB);
- System.out.println(checkIfRectangular(matrixA));
- System.out.println("Subtracting A + B");
- int[][] resultAPlusB = subtractMatrixAB(matrixA, matrixB);
- printMatrix(resultAPlusB);
- }
- //adds A and B
- public static int[][] addMatrixAB(int[][] a, int[][] b) {
- int[][] resultingMatrix = new int[a.length][a[0].length];
- //validation
- //A and B both need to be m x n in dimensions or else it would not work
- if ((a.length == b.length) && (checkIfRectangular(a)) && checkIfRectangular(b)) {
- for (int i = 0; i < a.length; i++) {
- for (int j = 0; j < a[i].length; j++) {
- resultingMatrix[i][j] = a[i][j] + b[i][j];
- }
- }
- }
- else {
- System.out.println("error: Matrix must have the same dimensions / each matrix must have equal columns");
- return new int[][] {{4}};
- }
- return resultingMatrix;
- }
- //subtracts B from A
- public static int[][] subtractMatrixAB(int[][] a, int[][] b) {
- int[][] resultingMatrix = new int[a.length][a[0].length];
- //validation
- //A and B both need to be m x n in dimensions or else it would not work
- if ((a.length == b.length) && (checkIfRectangular(a)) && checkIfRectangular(b)) {
- for (int i = 0; i < a.length; i++) {
- for (int j = 0; j < a[i].length; j++) {
- resultingMatrix[i][j] = a[i][j] - b[i][j];
- }
- }
- }
- else {
- System.out.println("error: Matrix must have the same dimensions / each matrix must have equal columns");
- return new int[][] {{4}};
- }
- return resultingMatrix;
- }
- private static boolean checkIfRectangular(int[][] x) {
- //get length of the first subarray
- int subArraylength = x[0].length;
- for (int i = 0; i < x.length; i++) {
- if (x[i].length != subArraylength) {
- return false;
- }
- }
- return true;
- }
- public static void printMatrix(int[][] x) {
- for (int[] i : x) {
- for (int j : i) {
- System.out.print(j + "\t");
- }
- System.out.println("\n");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement