📜  两个矩阵相减的Java程序

📅  最后修改于: 2022-05-13 01:55:23.428000             🧑  作者: Mango

两个矩阵相减的Java程序

下面给出两个矩阵 A 和 B,任务是将它们相减,并且为了减去矩阵,两个矩阵的大小应该相同,即两个矩阵都必须具有 NXM 维度。

例子:

Input : A[][] = {{3, 1}, 
                 {2, 4}}
        B[][] = {{1, 1}, 
                 {2, 1}}
Output: {{2, 0}, 
         {0, 3}}
Input : A[][] = {{1, 2}, 
                 {3, 4}}
        B[][] = {{6, 4}, 
                 {1, 3}}       
Output: {{-5, -2}, 
         {2, 1}}

方法:

  • 初始化大小相等的两个矩阵,因为要执行减法,两个矩阵的大小应该相同。
  • 分配两个矩阵中的值。
  • 创建一个与Matrix1和Matrix2大小相同的新矩阵,用于存储减法后的结果。
  • 在 for 循环的帮助下遍历矩阵,并对两个矩阵执行减法。并将结果存储在结果矩阵中。
  • 打印最终结果矩阵。

下面是上述方法的实现:

Java
// Java Program to Subtract the Two Matrices
  
import java.io.*;
  
class GFG {
  
    // Function to print Matrix
    static void printMatrix(int M[][], int rowSize,
                            int colSize)
    {
        for (int i = 0; i < rowSize; i++) {
            for (int j = 0; j < colSize; j++)
                System.out.print(M[i][j] + " ");
  
            System.out.println();
        }
    }
  
    // Function to subtract the two matrices
    // and store in matrix C
    static int[][] subtract(int A[][], int B[][], int size)
    {
        int i, j;
        int C[][] = new int[size][size];
  
        for (i = 0; i < size; i++)
            for (j = 0; j < size; j++)
                C[i][j] = A[i][j] + B[i][j];
  
        return C;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int size = 3;
  
        int A[][] = { { 50, 20, 30 },
                      { 60, 30, 10 },
                      { 30, 80, 10 } };
        // Print the matrices A
        System.out.println("\nMatrix A:");
        printMatrix(A, size, size);
  
        int B[][] = { { 10, 10, 5 },
                      { 20, 10, 12 },
                      { 23, 21, 12 } };
        // Print the matrices B
        System.out.println("\nMatrix B:");
        printMatrix(B, size, size);
  
        // Add the two matrices
        int C[][] = subtract(A, B, size);
  
        // Print the result
        System.out.println("\nResultant Matrix:");
        printMatrix(C, size, size);
    }
}


输出
Matrix A:
50 20 30 
60 30 10 
30 80 10 

Matrix B:
10 10 5 
20 10 12 
23 21 12 

Resultant Matrix:
60 30 35 
80 40 22 
53 101 22 

时间复杂度: O(N x M),其中 N x M 是矩阵的维度。