Product of Matrices

Asked

Viewed 5,027 times

1

I am trying to create a method that returns the product of two matrices passed as parameter. The method is working only for square matrices and not for two 2x3 and 3x2 matrices, for example. If anyone can help and tell me where the mistake is, I’d appreciate it.

  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;
}

2 answers

1

The error in your code is in the way you index matrices. 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 little bit and remove the variables somatoria and produto. 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 ;
}

-1

Mine worked, only I know c is the best possible

    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;
        }
    }

Browser other questions tagged

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