user3419155
user3419155

Reputation: 39

Multiplication of matrices/ arrays in java

Hi I have this code for multiplication of matrices in Java. It is working (no errors) but giving me wrong answer of the multiplied matrix. The two matrices which are to be multiplied have been defined properly. Here's the code:

// position_new = multiply ( transformation (3x3) * transpose(3x1)  )
int rows=3, columns=1;
double multiply[][] = new double[rows][columns];
double sum;

for (int k = 0; k < columns; k++) {
    for (int e = 0; e < rows; e++) {
        sum = 0;
        for (int f = 0; f < columns; f++) {
            sum = sum + transformation[e][f] * transpose[f][k];
        }
        multiply[e][k] = sum;
    }
}
System.out.println("Multiplied Matrix:-");
for (int m = 0; m < rows; m++) {
    for (int n = 0; n < columns; n++)
        System.out.print(multiply[m][n] + "\t");
    System.out.print("\n");
} 

Thanks a lot for the help in advance.

Upvotes: 0

Views: 1876

Answers (2)

Jamey
Jamey

Reputation: 843

your column/row variables are incorrect, it should be this:

// position_new = multiply ( transformation (mxn) * transpose(nxp)  )
int m = 3, n = 3, p = 1;
double multiply[][] = new double[m][p];
double sum;

for (int k = 0; k < p; k++) {
    for (int e = 0; e < m; e++) {
        sum = 0;
        for (int f = 0; f < n; f++) {
            sum = sum + transformation[e][f] * transpose[f][k];
        }
        multiply[e][k] = sum;
    }
}
System.out.println("Multiplied Matrix:-");
for (int i = 0; i < m; i++) {
    for (int j = 0; j < p; j++)
        System.out.print(multiply[i][j] + "\t");
        System.out.print("\n");
}  

With the example you gave you were only looping over the first column of the transformation matrix (because columns == 1) This means you were doing a 1x3 * 3x1 matrix multiplication. :)

Upvotes: 0

Andynedine
Andynedine

Reputation: 441

public void Miltiply(){
    // position_new = multiply ( transformation (3x3) * transpose(3x1)  )
    int rows=3, columns=1;
    int transformation[][]={{1,2,3},{1,1,1},{2,2,2}};
    int transpose[][]={{1},{1},{1}};
    double multiply[][] = new double[rows][columns];
    double sum;

    for (int k = 0; k < transpose[0].length; k++) {
        for (int e = 0; e < transformation.length; e++) {
            sum = 0;
            for (int f = 0; f < transpose.length; f++) {
                sum = sum + transformation[e][f] * transpose[f][k];
            }
            multiply[e][k] = sum;
        }
    }
    System.out.println("Multiplied Matrix:-");
    for (int m = 0; m < rows; m++) {
        for (int n = 0; n < columns; n++)
            System.out.print(multiply[m][n] + "\t");
        System.out.print("\n");
    } 
}

Output (M_3x3 X M_3x1 = M_3x1):

6.0 
3.0 
6.0

Upvotes: 1

Related Questions