Giới thiệu
Trong bài viết này, chúng ta sẽ tìm hiểu cách tính Trace (dấu vết) và Normal (chuẩn) của ma trận. Normal là căn bậc hai của tổng bình phương tất cả các phần tử. Trace là tổng các phần tử trên đường chéo chính (góc trên trái đến góc dưới phải).
Minh họa
Đầu vào:
The matrix is defined as: 2 3 4 5 2 3 4 6 9
Đầu ra mong muốn:
Trace value: 13.0 Normal value: 14.142135623730951
Thuật toán
- Bắt đầu
- Khai báo ma trận số nguyên
input_matrix - Khởi tạo giá trị
- Tính Trace: duyệt ma trận, cộng các phần tử đường chéo (i == j)
- Tính Normal: duyệt ma trận, tính tổng bình phương từng phần tử, rồi căn bậc hai
- Hiển thị kết quả
- Kết thúc
Ví dụ 1: Triển khai trong hàm main
public class NormalAndTrace {
public static void main(String args[]) {
int[][] input_matrix = {
{2, 3, 4},
{5, 2, 3},
{4, 6, 9}
};
int i, j, matrix_size = 3;
double trace = 0, square = 0, normal = 0;
System.out.println("The matrix is defined as: ");
for(i = 0; i < matrix_size; i++) {
for(j = 0; j < matrix_size; j++)
System.out.print(input_matrix[i][j] + " ");
System.out.println(" ");
}
System.out.println("\nThe Trace value of the matrix is ");
for(i = 0; i < matrix_size; i++) {
for(j = 0; j < matrix_size; j++) {
if(i == j) {
trace = trace + (input_matrix[i][j]);
}
}
}
System.out.println(trace);
System.out.println("\nThe Normal value of the matrix is ");
for(i = 0; i < matrix_size; i++) {
for(j = 0; j < matrix_size; j++) {
square = square + (input_matrix[i][j]) * (input_matrix[i][j]);
}
}
normal = Math.sqrt(square);
System.out.println(normal);
}
}
Đầu ra
The matrix is defined as: 2 3 4 5 2 3 4 6 9 The Trace value of the matrix is 13.0 The Normal value of the matrix is 14.142135623730951
Ví dụ 2: Tách hàm static (OOP)
public class NormalAndTrace {
static int matrix_size = 3;
static void normal_trace(int input_matrix[][]) {
int i, j;
double trace = 0, square = 0, normal = 0;
System.out.println("\nThe Trace value of the matrix is ");
for(i = 0; i < matrix_size; i++) {
for(j = 0; j < matrix_size; j++) {
if(i == j) {
trace = trace + (input_matrix[i][j]);
}
}
}
System.out.println(trace);
System.out.println("\nThe Normal value of the matrix is ");
for(i = 0; i < matrix_size; i++) {
for(j = 0; j < matrix_size; j++) {
square = square + (input_matrix[i][j]) * (input_matrix[i][j]);
}
}
normal = Math.sqrt(square);
System.out.println(normal);
}
public static void main(String args[]) {
int i, j;
int[][] input_matrix = { {2, 3, 4}, {5, 2, 3}, {4, 6, 9} };
System.out.println("The matrix is defined as: ");
for(i = 0; i < matrix_size; i++) {
for(j = 0; j < matrix_size; j++)
System.out.print(input_matrix[i][j] + " ");
System.out.println(" ");
}
normal_trace(input_matrix);
}
}
Đầu ra
The matrix is defined as: 2 3 4 5 2 3 4 6 9 The Trace value of the matrix is 13.0 The Normal value of the matrix is 14.142135623730951