Java程序用于减去两个矩阵


对于两个给定的m×n大小的矩阵,编写一个Java程序来减去它们。矩阵具有其元素的行和列排列。具有m行和n列的矩阵可以称为m×n矩阵。矩阵中的单个条目称为元素,可以用a[i][j]表示,这意味着元素a位于第i行和第j列。

请注意,只有当每个矩阵的行数和列数相等时,才能减去两个矩阵。现在,让我们用一个示例场景来理解问题陈述:

示例场景

Input 1: matrix1 = {{2, 3, 4}, {5, 2, 3}, {4, 6, 9}}
Input 2: matrix2 = {{1, 5, 3}, {5, 6, 3}, {8, 1, 5}}
Output: res = {{1, -2, 1}, {0, -4, 0}, {-4, 5, 4}}  

使用嵌套for循环

在这种方法中,使用外循环迭代两个矩阵的每个元素,并使用内循环将第一个矩阵中[i][j]位置的元素与第二个矩阵中[i][j]位置的元素相减,并将值存储在结果矩阵的[i][j]位置。

示例

在这个Java程序中,我们使用嵌套for循环来减去两个矩阵。

public class Tester {
   public static void main(String args[]) {
      //matrix 1
      int a[][] = { { 1, 3, 4 }, { 2, 4, 3 }, { 3, 4, 5 } };
      //matrix 2
      int b[][] = { { 1, 3, 4 }, { 2, 4, 3 }, { 1, 2, 4 } };
      //result matrix with 3 rows and 3 columns
      int c[][] = new int[3][3];
	  System.out.println("The result after subtraction of the given matrices is:");
      // subtract and print matrix
      for (int i = 0; i < 3; i++) {
         for (int j = 0; j < 3; j++) {
            c[i][j] = a[i][j] - b[i][j];
            System.out.print(c[i][j] + " ");
         }
         System.out.println();
      }
   }
}

上述代码的输出如下:

The result after subtraction of the given matrices is:
0 0 0 
0 0 0 
2 2 1 

使用嵌套while循环

这是在Java中减去两个矩阵的另一种方法。在这里,我们使用嵌套while循环代替嵌套for循环。实现使用了与前一个示例相同的逻辑。

示例

在这里,我们使用嵌套while循环在Java中减去两个矩阵。

public class SubtractMatrices {
   public static void main(String args[]) {
      int mtr1[][] = { {1, 7}, {9, 2} };
      int mtr2[][] = { {6, 3}, {5, 1} };
      int subtract[][] = new int[2][2];
      int matrix_size = 2;
      System.out.println("First matrix defined as::");
      for (int i = 0; i < matrix_size; i++) {
         for (int j = 0; j < matrix_size; j++) {
            System.out.print(mtr1[i][j] + "\t");
         }
         System.out.println();
      }
      
      System.out.println("Second matrix defined as::");
      for (int i = 0; i < matrix_size; i++) {
         for (int j = 0; j < matrix_size; j++) {
            System.out.print(mtr2[i][j] + "\t");
         }
         System.out.println();
      }
      
      int i = 0;
      while(i < matrix_size) {
         int j = 0;
         while(j < matrix_size) {
            subtract[i][j] = mtr1[i][j] - mtr2[i][j]; 
            j++;
         }
         i++;
      }
      
      System.out.println("Difference betwen given matrices is:: ");
      i = 0;
      while(i < matrix_size) {
         int j = 0;
         while(j < matrix_size) {
            System.out.print(subtract[i][j] + "\t");
            j++;
         }
         System.out.println();
         i++;
      }
   }
}

运行上述代码后,将显示以下输出:

First matrix defined as::
1	7	
9	2	
Second matrix defined as::
6	3	
5	1	
Difference betwen given matrices is:: 
-5	4	
4	1

更新于:2024年9月13日

859 次浏览

启动您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.