Java两个矩阵的乘积
在此程序中,我们需要将两个矩阵相乘并打印结果矩阵。
两个矩阵的乘积
两个矩阵的乘积可以通过将第一个矩阵的第一行的元素与第二个矩阵的第一列相乘,然后加上所有元素的乘积来计算。继续此过程,直到第一个矩阵的每一行与第二个矩阵的每一列相乘。
考虑上面的示例,可以通过乘以第一矩阵的第一行来计算结果矩阵prod [0,0]中的第一个元素,即( 1,3,2),第二矩阵的第一列即(2,1,1),最后求和所有元素的乘积,即(1 * 2)+(3 * 1)+(2 * 1)= 7。 ,第二项prod [0,1]可以通过将第一矩阵的第一行与第二矩阵的第二列相乘并求和所有乘积来求出。
当且仅当两个矩阵可以相乘如果满足以下条件:
第一个矩阵中的列数应等于第二个矩阵中的行数。
假设矩阵A的维数为p×q,矩阵B的维数为q×r,则所得矩阵的维数将为p×r。矩阵乘法可以表示为
C<sub>ij</sub>=ΣA<sub>ik</sub>B<sub>kj</sub>
算法
步骤1: START
步骤2: 定义row1,col1,row2,col2
步骤3: 初始化矩阵a[][] = {{1,3,2},{3,1,1},{1,2,2}}
步骤4: 初始化矩阵b[][] = {{2,1,1},{1,0,1},{1,3,1}}
步骤5: row1 = a.length
步骤6: col1 = a [0].length
步骤7: row2 = b.length
步骤8: row2 = b [0].length
步骤9: if(col1!= row2)
打印"矩阵不能相乘"
else
转到步骤10;
步骤10: prod[][] = [row1][col2]
步骤11: 直到i < row1
////for(i = 0; i < row1; i ++),将步骤12重复到步骤14
步骤12: 将步骤13重复到步骤14直到j < col2//for(j=0; j < col2; j++)
If(j> i)然后PRINT 0 else 打印a[i][j]
步骤13: 重复步骤14,直到k < row2 //for(k=0; k < row2; k ++)
步骤14: prod [i] [j] = prod [i] [j] + a [i] [k] * b [k] [j]
步骤15: ,直到i < row1 重复步骤16至步骤18
步骤16: ,直到j < col2 重复步骤17
步骤17: 打印prod[i] [j]
步骤18: 打印新行
步骤19: END
程序
public class ProdMatrix
{
public static void main(String[] args) {
int row1, col1, row2, col2;
//Initialize matrix a
int a[][] = {
{1, 3, 2},
{3, 1, 1},
{1, 2, 2}
};
//Initialize matrix b
int b[][] = {
{2, 1, 1},
{1, 0, 1},
{1, 3, 1}
};
//Calculates number of rows and columns present in first matrix
row1 = a.length;
col1 = a[0].length;
//Calculates the number of rows and columns present in the second matrix
row2 = b.length;
col2 = b[0].length;
//for two matrices to be multiplied,
//number of columns in first matrix must be equal to number of rows in second matrix
if(col1 != row2){
System.out.println("Matrices cannot be multiplied");
}
else{
//Array prod will hold the result
int prod[][] = new int[row1][col2];
//Performs product of matrices a and b. Store the result in matrix prod
for(int i = 0;i <row1;i++){
for(int j = 0;j <col2;j++){
for(int k = 0;k <row2;k++){
prod[i][j] = prod[i][j] + a[i][k] * b[k][j];
}
}
}
System.out.println("Product of two matrices: ");
for(int i = 0; <row1;i++){
for(int j = 0;j <col2;j++){
System.out.print(prod[i][j] + " ");
}
System.out.println();
}
}
}
}
输出:
Product of two matrices
7 7 6
8 6 5
6 7 5