簡體   English   中英

在Java中計算鄰接矩陣

[英]Calculate adjacency matrices in java

基本上,我需要向用戶查詢矩陣。 然后我需要找到A ^ 2,A ^ 3,A ^ 4 ...等(其中A是矩陣)。 然后我需要找到總和A + A ^ 2 + A ^ 3 ...等等直到6。

到目前為止,這是我所做的

public class Driver {

public static void main(String[] args) {
        int i, j, l, k, sum   =   0   ;
        int matrixAColumnSize         ;
        int matrixARowSize            ;
        double numberOfNodes             ;

        // Querying user for matrix size
        matrixARowSize      =   Tools.queryForInt("Enter the row size of Matrix A: ") ;
        matrixAColumnSize   =   Tools.queryForInt("Enter the column size of Matrix A: ") ;

        // Creating Matrices
        double matrixA[][]       =   new double[matrixARowSize][matrixAColumnSize] ;
        double finalMatrix[][]   =   new double [matrixARowSize][matrixAColumnSize] ;
        double tempMatrix[][]    =   new double[matrixARowSize][matrixAColumnSize] ;

        numberOfNodes   =   Tools.queryForInt("Enter by how much you'd like to raise to the power: ") ;

        // Creating Matrix A
        for (i = 0; i < matrixARowSize; i++) {
            for (j = 0; j < matrixAColumnSize; j++) {
                matrixA[i][j] = Tools.queryForInt("Enter element in Matrix A" + (i+1) + "," + (j+1) + ": " ) ; }}

        // Math
        for (i = 0; i < matrixARowSize; i++)
        {
            for (j = 0; j < matrixAColumnSize; j++) 
            {
                { 
                sum += Math.pow(matrixA[i][j], numberOfNodes) ;
                }

                finalMatrix[i][j] = sum ;
                sum = 0;

            }} 
        //Printing out matrix
        System.out.println("Final: ") ;

        for (i = 0; i < matrixARowSize; i++) {
            for (j = 0; j < matrixAColumnSize; j++) 
                System.out.print(finalMatrix[i][j] + "\t") ;

            System.out.println();
}

}}

它不起作用... :(哈哈

PS:Tools.queryForInt是我創建的用於查詢用戶的方法...

該程序本身正在運行,但結果不正確。 例如,

2 2    *  2 2    =   8 8
2 2       2 2        8 8

該程序會給我

4 4
4 4

因此,當我提高到2的冪時,它只是將數組中的所有內容都提高了2 ...

您計算矩陣的方式不正確。 實際上,您是在計算單個矩陣元素的功效。 在乘以矩陣之前,應檢查其尺寸。 對於AxB,A中的列數應等於B中的列數。由於您要將矩陣與其自身相乘,因此它應該是方矩陣。

這是我用來將兩個矩陣相乘的代碼。 您可以修改此代碼以適合您的要求。 我建議遞歸或迭代地調用此模塊

for(int i=0;i<row;i++){
  for(int j=0;i<col;i++){
    for(int k=0;i<row;i++){
      matrix[i][j]+=(A[i][k]*B[k][j]);
    } 
  }
}

暫無
暫無

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

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