Multiplication of 3 matrices

Asked

Viewed 50 times

0

I have to multiply three matrices with the validation that you can actually do, in one function. I’m trying to do matrix 1 and 2 first and get the result to do the 3. But it’s going wrong and also I can’t call the result on main.

 public static int[][] mult(int linha, int coluna, int linha2, int coluna2, int linha3, int coluna3, int[][] matriz, int[][] matriz2, int[][] matriz3) {

            if(matriz[0].length == matriz2.length){
                int[][] matrizR = new int[linha][coluna2];
             
                for(int i = 0; i < linha; i++){
                    for(int j = 0; j < coluna2; j++)
                        for(int k = 0; k < linha2; k++)
                            matrizR[i][j] = matriz[i][k] * matriz2[k][j];
                }
                return matrizR;
            }
            if(matrizR[0].length == matriz3.length){
               int[][] resultado = new int[linha][coluna3];
              
               for(int i = 0; i < linha; i++){
                   for(int j = 0; j < coluna3; j++)
                       for(int k = 0; k < linha2; k++)
                           resultado[i][j] = matrizR[i][k] * matriz3[k][j];
               }
               return resultado;
           }
      }

1 answer

0

To multiply 2 matrices, the number of columns of the first must be equal to the number of rows of the second. That is, if the first matrix is M x N (M rows and N columns), the second must be N x P (N rows and P columns) and the result will be a matrix M x P (M rows and P columns).

Anyway, I find it easier to make a method that multiplies 2 matrices, and then you can use to multiply as many as you want later. And the algorithm is wrong on the last for you have to add to the value of the cell, but you’re overwriting it (see here the algorithm).

In the cases below I’m not checking if all rows in the matrix have the same amount of columns (I’m assuming this has been checked before). And also do not need to pass the number of rows and columns, as it is possible to get this from the matrices themselves:

// multiplica apenas 2 matrizes
public static int[][] mult(int[][] m1, int[][] m2) {
    if (m1[0].length != m2.length) { // se a quantidade de coluunas de m1 é diferente da quantidade de linhas de m2
        throw new IllegalArgumentException("Não é possível multiplicar, tamanhos incompatíveis");
    }

    int[][] result = new int[m1.length][m2[0].length];
    for (int lin = 0; lin < result.length; lin++) {
        for (int col = 0; col < result[lin].length; col++) {
            int valor = 0;
            for (int i = 0; i < m2.length; i++) {
                valor += m1[lin][i] * m2[i][col]; // soma ao valor ("+=" em vez de "=")
            }
            result[lin][col] = valor;
        }
    }
    return result;
}

So, if you want to multiply 3 matrices, just use the above method by multiplying 2 by 2:

// multiplica 3 matrizes
public static int[][] multiplicaTrezMatrizes(int[][] m1, int[][] m2, int[][] m3) {
    // primeiro multiplica m1 e m2
    int[][] result = mult(m1, m2);

    // depois multiplica por m3
    return mult(result, m3);
}

Or, if you want to make a generic method that receives any number of matrices:

public static int[][] multiplicaVariasMatrizes(int[][]... matrizes) {
    int[][] result = matrizes[0]; // pega a primeira matriz
    for (int i = 1; i < result.length; i++) { // vai multiplicando as matrizes
        result = mult(result, matrizes[i]);
    }
    return result;
}

// e no main:
int[][] m1 = { new int[] { 1, 2 }, new int[] { 3, 4 }, new int[] { 5, 6 } };
int[][] m2 = { new int[] { 1, 2, 3, 4 }, new int[] { 5, 6, 7, 8 } };
int[][] m3 = { new int[] { 1, 2 }, new int[] { 3, 4 }, new int[] { 5, 6 }, new int[] { 7, 8 } };

System.out.println(Arrays.deepToString(multiplicaVariasMatrizes(m1, m2, m3)));

Browser other questions tagged

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