Java 程式用於查詢給定矩陣的跡和法向
在本文中,我們將瞭解如何查詢給定矩陣的跡和法向。矩陣的法向是一個矩陣中所有元素平方和的平方根。矩陣的跡是一個矩陣的主對角線上的所有元素的和(從左上到右下)。
以下是對此的演示 −
假設我們的輸入為 −
The matrix is defined as: 2 3 4 5 2 3 4 6 9
理想的輸出是 −
Trace value: 13.0 Normal value: 14.142135623730951
演算法
Step 1 - START Step 2 - Declare an integer matrix namely input_matrix Step 3 - Define the values. Step 4 - To compute trace value, iterate over each element of the matrix using two for-loops, add the diagonal elements and store the value. Step 5 - To compute the normal value, iterate over each element of the matrix using two for-loops, compute the sum of square of each element, them compute the square root of the value and store the value. Step 5 - Display the result Step 6 - Stop
示例 1
這裡,我們將所有操作繫結在一起,納入“主體”函式。
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);
}
}輸出
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
示例 2
這裡,我們將操作封裝到函式中,體現面向物件程式設計。
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);
}
}輸出
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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP