Product of Matrices

1

I am trying to create a method that returns the product of two arrays passed as parameter. The method is only working for square matrices and not for two 2x3 and 3x2 matrices, for example. If anyone can help and tell you where the error is, I thank you.

  public static int[][] calculaProduto(int[][] a, int[][] b) {
    int[][] result = new int[ a.length ][ b[0].length ];


    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < b[0].length; j++) {
            int somatoria = 0;
            for (int k = 0; k < a.length; k++) {
                // A: (0x0) * B:(0x0) + A:(0x1) * B:(1x0)...
                // 
                //

                int produto = a[j][k] * b[k][j];
                somatoria += produto;
                result[i][j] = somatoria;
            }
        }
    }
    return result;
}
    
asked by anonymous 26.05.2015 / 01:53

2 answers

1

The error in your code is in the way you index the arrays. Try it like this:

public static int[][] calculaProduto(int[][] a, int[][] b) {

    if (a[0].length != b.length) throw new RuntimeException("Dimensões inconsistentes. Impossível multiplicar as matrizes");

    int[][] result = new int[ a.length ][ b[0].length ];

    for (int i = 0; i < a.length; i++)
        for (int j = 0; j < b[0].length; j++) {
            int somatoria = 0;
            for (int k = 0; k < a[0].length; k++) {
                int produto = a[i][k] * b[k][j];
                somatoria += produto;
            }
            results[i][j] = somatoria ;
        }
    return result ;
}

You can simplify the code a bit and remove the variables somatoria and produto . It would look like this:

public static int[][] calculaProduto(int[][] a, int[][] b) {

    if (a[0].length != b.length) throw new RuntimeException("Dimensões inconsistentes. Impossível multiplicar as matrizes");

    int[][] result = new int[ a.length ][ b[0].length ];

    for (int i = 0; i < a.length; i++)
        for (int j = 0; j < b[0].length; j++) 
            for (int k = 0; k < a[0].length; k++) 
                results[i][j] += (a[i][k] * b[k][j]);
    return result ;
}
    
26.05.2015 / 11:49
-1

My luck, I just do not know what's best

    for(i=0; i<4; i++){
        int linha = 1;
        for(j=0;j<4;j++){
            linha *= ma[i][j];
        }
        for(z=0;z<4;z++){
            int col = 1;
            for(l=0;l<4;l++){
                col *= ma[i][j];
            }
            prod[i][z] = col + linha;
        }
    }
    
23.09.2018 / 18:30