簡體   English   中英

Java中矩陣/數組的乘法

[英]Multiplication of matrices/ arrays in java

嗨,我有這段代碼用於Java中的矩陣乘法。 它正在工作(沒有錯誤),但是給我乘法矩陣的錯誤答案。 要相乘的兩個矩陣已正確定義。 這是代碼:

// 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");
} 

非常感謝您的事先幫助。

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

輸出(M_3x3 X M_3x1 = M_3x1):

6.0 
3.0 
6.0

您的列/行變量不正確,應該是這樣的:

// 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");
}  

在給出的示例中,您僅循環了轉換矩陣的第一列(因為column == 1),這意味着您正在執行1x3 * 3x1的矩陣乘法。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM