![](/img/trans.png)
[英]Computing the sum of each column in a matrix returns the same result for every column
[英]Computing Sum of Multiplication of Matrix Exponents
我遇到了以下问题:
对于给定的指数N,2×2矩阵A和极限L,递归计算矩阵S:
S = I + A + A ^ 2 + A ^ 3 + ... + A ^ N.
我是身份矩阵。
如果矩阵S的任何元素大于或等于L.减去L,直到它低于L.
我的算法如下:
// Pre-condition:
// Parameters:
// An integer indicating an exponent
// A 2d 2x2 integer array must exist as an instance attribute
// Post-condition: The matrix resulting from the sum of multiplied matrices
// i.e. A^2 + A^1 + I
public int[][] computeMatrixSum(int exp)
{
if(exp == 0)
{
return new int[][]
{
new int[]{ 1,0 },
new int[]{ 0,1 }
};
}
else
{
int[][] matrixB = new int[matrix.length][matrix[0].length];
int[][] matrixC = new int[matrix.length][matrix[0].length];
matrixB = matrix;
for(int expC = exp; expC > 1; expC--)
{
// Multiply the matrix
for(int i = 0; i < matrix.length; i++)
{
for(int k = 0; k < matrixB[0].length; k++)
{
for(int j = 0; j < matrix[0].length; j++)
{
matrixC[i][k] += matrix[i][j] * matrixB[j][k];
}
}
}
matrixB = matrixC;
matrixC = new int[matrix.length][matrix[0].length];
}
// Recursively calculate the sum of the other matrix products
int[][] tmpSum = computeMatrixSum(exp-1);
int[][] matrixSum = new int[matrixB.length][matrixB[0].length];
for(int row = 0; row < matrixB.length; row++)
{
for(int col = 0; col < matrixB[0].length; col++)
{
matrixSum[row][col] = matrixB[row][col] + tmpSum[row][col];
}
}
return matrixSum;
}
}
// Pre-condition:
// Parameters:
// An integer indicating the exponent to apply on the matrix
// An integer indicating the limit of the elements of the 2d matrix sum
// An 2d 2x2 integer array must exist as an instance attribute
// Post-condition: The matrix resulting from the sum of multiplied matrices
// that has elements that are not greater than the given limit
// i.e. A^2 + A^1 + I
public int[][] solve(int exp,int limit)
{
int[][] matrixSum = computeMatrixSum(exp);
for(int row = 0; row < matrixSum.length; row++)
{
for(int col = 0; col < matrixSum.length; col++)
{
while(matrixSum[row][col] >= limit)
matrixSum[row][col] -= limit;
}
}
return matrixSum;
}
我的算法有效。 但是对于大的N值来说,它太慢了。这是因为当我乘以它时,我会不断重新计算所有指数的结果。
我不知道任何其他算法在解决这个问题上更有效率。
有人可以建议吗?
谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.