[英]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.