이 기사에서는 상부 삼각 행렬을 표시하는 방법을 이해할 것입니다. 행렬에는 요소의 행과 열 배열이 있습니다. m개의 행과 n개의 열로 구성된 행렬을 m × n 행렬이라고 할 수 있습니다. 상부 삼각 행렬은 주대각선 아래의 모든 요소가 0인 삼각 행렬입니다.
아래는 동일한 데모입니다 -
입력이 다음과 같다고 가정 -
The matrix is defined as: 2 1 4 1 2 3 3 6 2
원하는 출력은 -
The upper triangular matrix is: 2 1 4 0 2 3 0 0 2
알고리즘
Step 1 - START Step 2 - Declare an integer matrix namely input_matrix. Step 3 - Define the values. Step 4 - Iterate over each element of the matrix using two for-loops, assign 0 to all the [i][j] positions that comes below the diagonal of the matrix using rows != column condition. Step 5 - Display the matrix as result Step 6 - Stop
예시 1
여기에서 모든 작업을 'main' 기능 아래에 묶습니다.
public class UpperTriangle { public static void upper_triangular_matrix(int input_matrix[][]) { } public static void main(String[] args) { int input_matrix[][] = { { 2, 1, 4 }, { 1, 2, 3 }, { 3, 6, 2 } }; int rows = input_matrix.length; int column = input_matrix[0].length; System.out.println("The matrix is defined as: "); for (int i = 0; i < rows; i++) { for (int j = 0; j < column; j++) { System.out.print(input_matrix[i][j] + " "); } System.out.println(); } if (rows != column) { return; } else { for (int i = 0; i < rows; i++) { for (int j = 0; j < column; j++) { if (i > j) { input_matrix[i][j] = 0; } } } System.out.println("\nThe upper triangular matrix is: "); for (int i = 0; i < rows; i++) { for (int j = 0; j < column; j++) { System.out.print(input_matrix[i][j] + " "); } System.out.println(); } } } }
출력
The matrix is defined as: 2 1 4 1 2 3 3 6 2 The upper triangular matrix is: 2 1 4 0 2 3 0 0 2
예시 2
여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.
public class UpperTriangle { public static void upper_triangular_matrix(int input_matrix[][]) { int rows = input_matrix.length; int column = input_matrix[0].length; if (rows != column) { return; } else { for (int i = 0; i < rows; i++) { for (int j = 0; j < column; j++) { if (i > j) { input_matrix[i][j] = 0; } } } System.out.println("\nThe upper triangular matrix is: "); for (int i = 0; i < rows; i++) { for (int j = 0; j < column; j++) { System.out.print(input_matrix[i][j] + " "); } System.out.println(); } } } public static void main(String[] args) { int input_matrix[][] = { { 2, 1, 4 }, { 1, 2, 3 }, { 3, 6, 2 } }; int rows = input_matrix.length; int column = input_matrix[0].length; System.out.println("The matrix is defined as: "); for (int i = 0; i < rows; i++) { for (int j = 0; j < column; j++) { System.out.print(input_matrix[i][j] + " "); } System.out.println(); } upper_triangular_matrix(input_matrix); } }
출력
The matrix is defined as: 2 1 4 1 2 3 3 6 2 The upper triangular matrix is: 2 1 4 0 2 3 0 0 2