Sum of matrices in java matrix A+ matrizB, results in matrix C

Asked

Viewed 1,262 times

1

I need to make a matrix sum algorithm in Java, in which the sum of the matrix with the matrix B, generates the matrix C. if the matrizA has the same number of rows and columns as the matrix B.

Calculate and show a resulting matrix C of the sum of the matrix A and the matrix B. It is only possible to add the matrices if they are of the same order.

I really have no idea how to assemble this matrizC, follow the code I’ve gotten so far.

public static void main(String[] args) {

    int N = Integer.parseInt(JOptionPane.showInputDialog("Digite o numero de linhas da A"));
    int M = Integer.parseInt(JOptionPane.showInputDialog("Digite o numero de colunas da A"));
    int O = Integer.parseInt(JOptionPane.showInputDialog("Digite o numero de linhas da B"));
    int P = Integer.parseInt(JOptionPane.showInputDialog("Digite o numero de colunas da B"));

    int matrizA[][] = new int[N][M];
    int matrizB[][] = new int[O][P];

    for (int i = 0; i < matrizA.length; i++) {
        for (int j = 0; j < matrizA.length; j++) {

            matrizA[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Digite o " + (i + 1) + " valor da matriz A"));

        }

    }
    for (int i = 0; i < matrizB.length; i++) {
        for (int j = 0; j < matrizB.length; j++) {

            matrizB[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Digite o " + (j + 1) + " valor da matriz B"));
        }

    }

    int soma = 0;

    if (N == O && M == P) {

        for (int i = 0; i < matrizB.length; i++) {
            for (int j = 0; j < matrizB.length; j++) {

                soma = matrizA[i][j] + matrizB[i][j];

            }

        }

    }
  • 1

    Remains to declare the matrizC the size of one of the others and use it where the soma = ..., to keep matrizC[i][j] = ...

  • It worked! Thank you !

1 answer

0

Instead of this int sum, create the direct matrizC and assign the values.

int[][] matrizC;

if (N == O && M == P) {

    for (int i = 0; i < matrizB.length; i++) {
        for (int j = 0; j < matrizB.length; j++) {

            matrizC[i][j] = matrizA[i][j] + matrizB[i][j];
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.