Java两个矩阵相减
在此程序中,我们需要获得两个矩阵相减的结果。
两个矩阵A和B当且仅当它们具有相同的尺寸,相同的行和列数时,才可以减去。从3×2矩阵中减去2×3矩阵是不可能的。可以通过减去两个矩阵的相应元素来减去两个矩阵
(A - B)<sub>ij</sub>=A<sub>ij</sub>-B<sub>ij</sub>
两个矩阵的减法可以是通过遍历第一和第二矩阵来执行。计算它们对应元素之间的差异,并将结果存储在第三个矩阵中。
算法
步骤1: START
步骤2: 定义行,列
步骤3: 初始化第一个矩阵a [] [] = {{4,5,6},{3,4,1},{1,2,3}}
步骤4: 初始化第二个矩阵b [] [] = {{2,0,3},{2,3,1} {1,1,1}}
第5步: 行= a.length
步骤6: cols = a[0] .length
步骤7: 定义diff[][]
步骤8: 直到i < rows为止,将步骤9重复到步骤10 //for(i = 0; i < rows; i++)
步骤9: 重复步骤10直到j < cols ////for(j = 0; j < cols; j++)
步骤10: diff[i] [j] = a [i] [j]-b [i] [j]
步骤11: 打印"两个矩阵相减: "
步骤12: 直到i < rows 重复步骤13至14,//for(i = 0; i < rows; i++)
步骤13: 重复步骤14,直到j < cols ////for(j = 0; j < cols; j++)
步骤13: 打印差异[i] [j]
步骤14: 打印新行
STEP 15: END
程序:
public class Sub_Matrix
{
public static void main(String[] args) {
int rows, cols;
//Initialize matrix a
int a[][] = {
{4, 5, 6},
{3, 4, 1},
{1, 2, 3}
};
//Initialize matrix b
int b[][] = {
{2, 0, 3},
{2, 3, 1},
{1, 1, 1}
};
//Calculates number of rows and columns present in given matrix
rows = a.length;
cols = a[0].length;
//Array diff will hold the result
int diff[][] = new int[rows][cols];
//Performs subtraction of matrices a and b. Store the result in matrix diff
for(int i = 0;i <rows;i++){
for(int j = 0;j <cols;j++){
diff[i][j] = a[i][j] - b[i][j];
}
}
System.out.println("Subtraction of two matrices: ");
for(int i = 0;i <rows;i++){
for(int j = 0;j <cols;j++){
System.out.print(diff[i][j] + " ");
}
System.out.println();
}
}
}
输出:
Subtraction of two matrices:
1 5 3
1 1 0
0 1 2