提升矩阵的幂方法JAVA

1 java math matrix multiplication

我真的很难创建一种方法来提高矩阵的幂。我试过用这个

public static int powerMethod(int matrix, int power) {
    int temp = matrix ; 

    for (int i = power; i == 1; i--)
        temp = temp * matrix ; 



    return temp ;
Run Code Online (Sandbox Code Playgroud)

但回报是 WAYYY 关闭。只有第一个 (1,1) 矩阵元素是点。

我尝试在主程序中使用该方法

// Multiplying matrices
            for (i = 0; i < row; i++)
            {
                for (j = 0; j < column; j++) 
                {
                    for (l = 0; l < row; l++)
                    {
                        sum += matrix[i][l] * matrix[l][j] ;
                    }
                    matrix[i][j] = sum ;
                    sum = 0 ;
                }
                }

    // Solving Power of matrix
            for (i = 0; i < row; i++) {
                for (j = 0; j < column; j++) 
            matrixFinal[power][i][j] = Tools.powerMethod(matrix[i][j], power) ;
            }
Run Code Online (Sandbox Code Playgroud)

其中“power”、“row”和“column”是用户输入的整数。

任何想法我怎么能做到这一点?

谢谢!!!

Jas*_*n C 5

你这里有很多问题。

首先,您的矩阵平方算法有一个(常见)错误。你有:

for (i = 0; i < row; i++) {
    for (j = 0; j < column; j++) {
        for (l = 0; l < row; l++) {
            sum += matrix[i][l] * matrix[l][j] ;
        }
        matrix[i][j] = sum ;
        sum = 0 ;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,您需要将结果存储在临时的第二个矩阵中,因为当您这样做时matrix[i][j] = sum,它会用输出替换该位置的值,然后以后的结果最终会不正确。此外,我建议首先初始化sum为 0 ,因为看起来您在此循环之外声明了它,并且首先初始化它可以保护您免受进入循环之前可能具有的任何任意值的影响。此外,它不是立即清除您的意思和-确保您遍历整个矩阵。例如:sumrowcolumn

int temp[][] = new int[matrix.length];

for (i = 0; i < matrix.length; i++) {
    temp[i] = new int[matrix[i].length];
    for (j = 0; j < matrix[i].length; j++) {
        sum = 0 ;
        for (l = 0; l < matrix.length; l++) {
            sum += matrix[i][l] * matrix[l][j] ;
        }
        temp[i][j] = sum ;
    }
}

// the result is now in 'temp', you could do this if you wanted:
matrix = temp;
Run Code Online (Sandbox Code Playgroud)

请注意,如果矩阵是方阵(它必须是方阵,以便与自身相乘),则matrix.lengthmatrix[i].length上面可以互换。

其次,您的乘法对矩阵进行平方。这意味着如果你重复应用它,你每次都会对矩阵进行平方,这意味着你只能计算本身是 2 的幂的幂。

你的第三个问题是你的最后一点没有多大意义:

for (i = 0; i < row; i++) {
    for (j = 0; j < column; j++) 
        matrixFinal[power][i][j] = Tools.powerMethod(matrix[i][j], power) ;
}
Run Code Online (Sandbox Code Playgroud)

目前还不清楚您在这里尝试做什么。最后一部分似乎是试图将单个元素提升到一定的力量。但这与将矩阵提升为幂不同。

需要做的是定义一个适当的矩阵乘法方法,该方法可以将两个任意矩阵相乘,例如:

int[][] multiplyMatrices (int[][] a, int[][] b) {
    // compute and return a x b, similar to your existing multiplication
    // algorithm, and of course taking into account the comments about
    // the 'temp' output matrix above
}
Run Code Online (Sandbox Code Playgroud)

那么计算幂就变得简单了:

int[][] powerMatrix (int[][] a, int p) {
    int[][] result = a;
    for (int n = 1; n < p; ++ n)
        result = multiplyMatrices(result, a);
    return result;
}
Run Code Online (Sandbox Code Playgroud)