矩阵减法Java程序

时间:2020-01-09 10:35:34  来源:igfitidea点击:

这篇文章显示了一个Java程序减去两个矩阵。

当我们减去两个矩阵时,我们要减去两个矩阵中相同索引处的元素,因此我们要减去第一个矩阵中索引(0,0)处的元素,而第二个矩阵中索引(0,0)处的元素结果矩阵中(0,0)处的元素。还要注意,两个矩阵相减的阶数必须相同。

例如–如果要减去两个3 X 3矩阵。

矩阵减法的Java程序

import java.util.Scanner;

public class MatrixSubtraction {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.print("Enter number of rows and columns in the matrix : ");
		int row = in.nextInt();
		int column = in.nextInt();
		// First matrix
		int[][] matrix1 = prepareMatrix(row, column);
		
		// Second matrix
		int[][] matrix2 = prepareMatrix(row, column);
		// Subtraction result stored in this matrix
		int subtractMatrix[][] = new int[row][column];
		// Subtraction logic 
		for(int i = 0; i < row; i++){
			for(int j = 0; j < column; j++){
				subtractMatrix[i][j] = matrix1[i][j] - matrix2[i][j];
			}
		}
		
		System.out.println("Subtracted Matrix : " );
		for(int i = 0; i < subtractMatrix.length; i++){
			for(int j = 0; j < column; j++){
				System.out.print(" " +subtractMatrix[i][j]+"\t");
			}
			System.out.println();
		}
	}
	
	private static int[][] prepareMatrix(int row, int column){
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter elements of Matrix : ");
		int matrix[][] = new int[row][column];
		for(int i = 0; i < row; i++){
			for(int j = 0; j < column; j++){
				matrix[i][j] = sc.nextInt();
			}
		}
		System.out.println("Entered Matrix : " );
		for(int i = 0; i < row; i++){
			for(int j = 0; j < column; j++){
				System.out.print(" " +matrix[i][j]+"\t");
			}
			System.out.println();
		}
		return matrix;
	}
}

输出:

Enter number of rows and columns in the matrix :  3 3
Enter elements of Matrix : 1 3 8 2 9 3 0 5 11
Entered Matrix : 
 1	 3	 8	
 2	 9	 3	
 0	 5	 11	

Enter elements of Matrix : 0 2 4 6 7 8 2 3 5
Entered Matrix : 
 0	 2	 4	
 6	 7	 8	
 2	 3	 5
	
Subtracted Matrix : 
 1		1		4	
 -4		2		-5	
 -2		2		6