Sum of 3 matrices in a new matrix

Asked

Viewed 67 times

-1

I need a program that adds 3 matrices of Nxm size. The user should be able to set the size (Nxm) of the matrices. But I don’t know what’s wrong.

Java
        int linha = i;
        int coluna = j;
        int[][] matriz = new int[linha][coluna];
        int linha2 = i;
        int coluna2 = j;
        int[][] matriz2 = new int[linha2][coluna2];
        int linha3 = i;
        int coluna3 = j;
        int[][] matriz3 = new int[linha3][coluna3];

        Scanner input = new Scanner(System.in);
            //Definindo o tamanho (linha e coluna)
        System.out.print("Digite o tamanho da primeira matriz:\n ");
            matriz[linha][coluna]= input.nextInt();
        System.out.print("Digite o tamanho da segunda matriz:\n ");
            matriz2[linha2][coluna2] = input.nextInt();
        System.out.print("Digite o tamanho da terceira matriz:\n ");
            matriz3[linha3][coluna3] = input.nextInt();

        //Soma das 3 matrizes em uma nova matriz
        int[][] matrizR = new int[i][j];
        for(i = 0; i < matriz.length; i++)
        for(j = 0; j < matriz2.length; j++)
        for(k = 0; k < matriz3.length; k++)
        matrizR[i][j] = matriz[i][j] + matriz2[i][j] + matriz3[i][j];

2 answers

1

  1. The Java language allows you to declare multidimensional variables whose dimensions are variable. However, you are defining the dimensions of the matrices before reading them;
  2. The way you are reading the dimensions, you end up defining, at position [i, j] (which, by the code posted, do not have a value defined) the value defined by the user. It is necessary that you read the line, afterward the column and then instantiate the matrix with the values informed by the user;
  3. To obtain the sum of the two matrices, it is necessary, first, to obtain their values, reading element by element. Then, going through them, store in the third matrix the sum of the elements of the corresponding positions. With this in hand, it is possible to display the third matrix, traversing it and showing element by element.

1


You can only add matrices of the same size. If you have a matrix M x N (with M rows and N columns), you can only add it with another matrix M x N, and the result will be another matrix M x N. That is, it makes no sense to read the size of the 3 matrices, because the user can type different sizes for each one. What you have to do is read the size once, and then create the 3 matrices (plus the matrix that stores the sum result) with the same size.

Also, you have to read the number of rows and columns separately. And you only create the matrices afterward to read this data:

// primeiro lê os dados
Scanner input = new Scanner(System.in);
System.out.print("Digite a quantidade de linhas das matrizes: ");
int qtdLinhas = input.nextInt();
System.out.print("Digite a quantidade de colunas das matrizes: ");
int qtdColunas = input.nextInt();

// depois cria as matrizes
int[][] matriz1 = new int[qtdLinhas][qtdColunas];
int[][] matriz2 = new int[qtdLinhas][qtdColunas];
int[][] matriz3 = new int[qtdLinhas][qtdColunas];
int[][] resultado = new int[qtdLinhas][qtdColunas];

Once the matrices are created, you still need to fill in their values. One way to do it is to:

System.out.println("Lendo dados da matriz 1:");
for (int i = 0; i < matriz1.length; i++) {
    for (int j = 0; j < matriz1[i].length; j++) {
        System.out.printf("Digite o elemento da posição [%d, %d]: ", i, j);
        matriz1[i][j] = input.nextInt();
    }
}
System.out.println("Lendo dados da matriz 2:");
for (int i = 0; i < matriz2.length; i++) {
    for (int j = 0; j < matriz2[i].length; j++) {
        System.out.printf("Digite o elemento da posição [%d, %d]: ", i, j);
        matriz2[i][j] = input.nextInt();
    }
}
... fazer o mesmo para a matriz3

But notice how repetitive it is (I did basically the same thing twice, only changed from matriz1 for matriz2, and then switch back to matriz3), then you could create a method to fill any matrix:

static void lerDadosMatriz(Scanner input, int[][] m) {
    for (int i = 0; i < m.length; i++) {
        for (int j = 0; j < m[i].length; j++) {
            System.out.printf("Digite o elemento da posição [%d, %d]: ", i, j);
            m[i][j] = input.nextInt();
        }
    }
}

And then just use this method:

System.out.println("Lendo dados da matriz 1:");
lerDadosMatriz(input, matriz1);
System.out.println("Lendo dados da matriz 2:");
lerDadosMatriz(input, matriz2);
System.out.println("Lendo dados da matriz 3:");
lerDadosMatriz(input, matriz3);

Having the 3 matrices, to add just make one loop and add the values and keep in the result:

for (int i = 0; i < resultado.length; i++) {
    for (int j = 0; j < resultado[i].length; j++) {
        resultado[i][j] = matriz1[i][j] + matriz2[i][j] + matriz3[i][j];
    }
}

Ready!

If you want to display the result, just use one loop and print the values. It could be like for above, but if you only want the values and don’t need to know the contents, you can use a Enhanced for:

for (int[] linha : resultado) { // para cada linha da matriz
    for (int valor : linha) { // para cada valor da linha
        System.out.printf("%5d", valor); // alinhar o número à direita, usando 5 posições
    }
    System.out.println();
}

Browser other questions tagged

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