如果两个矩阵的行数和列数相等并且相应的元素也相等,则它们是相同的。一个例子如下。
Matrix A = 1 2 3 4 5 6 7 8 9 Matrix B = 1 2 3 4 5 6 7 8 9 The matrices A and B are identical
给出了一个检查两个矩阵是否相同的程序,如下所示。
public class Example { public static void main (String[] args) { int A[][] = { {7, 9, 2}, {3, 8, 6}, {1, 4, 2} }; int B[][] = { {7, 9, 2}, {3, 8, 6}, {1, 4, 2} }; int flag = 1; int n = 3; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (A[i][j] != B[i][j]) flag = 0; if (flag == 1) System.out.print("Both the matrices are identical"); else System.out.print("Both the matrices are not identical"); } }
输出结果
Both the matrices are identical
现在让我们了解上面的程序。
定义了两个矩阵A和B。flag的初始值为1。然后使用嵌套的for循环比较两个矩阵的每个元素。如果任何对应的元素不相等,则将flag的值设置为0。证明这一点的代码段如下所示-
int A[][] = { {7, 9, 2}, {3, 8, 6}, {1, 4, 2} }; int B[][] = { {7, 9, 2}, {3, 8, 6}, {1, 4, 2} }; int flag = 1; int n = 3; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (A[i][j] != B[i][j]) flag = 0;
如果flag为1,则矩阵相同,并显示出来。否则,矩阵不相同,将显示出来。证明这一点的代码片段如下所示-
if (flag == 1) System.out.print("Both the matrices are identical"); else System.out.print("Both the matrices are not identical");