Java 中檢查矩陣是否為馬爾可夫矩陣
矩陣只不過是二維矩形佈局中排列的資料元素的集合。在 Java 中,二維陣列可以被認為是矩陣。
如果所有元素都是非負的,並且每個列向量的和都等於 1,則方陣稱為馬爾可夫矩陣。馬爾可夫矩陣表示馬爾可夫鏈中的步驟。馬爾可夫矩陣的每個輸入都表示結果的機率。
讓我們深入研究這篇文章,瞭解如何使用 Java 程式語言來實現。
給你看一些例子
例項 1
Suppose we have a matrix | 0.10.50.4 | A= | 00.50.5 | | 0.90.10 |
所有行加起來等於 1。因此它是一個馬爾可夫矩陣。
例項 2
Suppose we have a matrix | 0.40.30.3 | A =| 0.50.30.2 | | 0.50.10.4 |
所有行加起來等於 1。因此它是一個馬爾可夫矩陣。
例項 3
Suppose we have a matrix | 1 0 0 0| A=| 0 1 0 0| | 0 0 1 0| | 0 0 0 1|
所有行加起來等於 1。因此它是一個馬爾可夫矩陣。
演算法
步驟 1 - 獲取矩陣。
步驟 2 - 現在呼叫檢查函式,該函式遍歷矩陣並檢查每一行的和是否等於 1。如果任何一行的元素加起來不等於 1,則該矩陣不是馬爾可夫矩陣。
步驟 3 - 列印結果。
多種方法
我們提供了多種方法的解決方案。
使用矩陣的靜態初始化。
使用矩陣的動態初始化。
讓我們逐一檢視程式及其輸出。
方法 1:使用矩陣的靜態初始化
在這種方法中,矩陣在程式中初始化,我們使用 for 迴圈計算每一行的和並檢查它是否加起來等於 1。
示例
import java.util.Scanner;
public class Main {
static boolean markovMatCheck(double mat[][]) {
double sum = 0;
// Traverses the matrix
for (int i = 0; i < mat.length; i++) {
sum = 0;
// Adds the row elements
for (int j = 0; j < mat.length; j++) {
sum += mat[i][j];
}
// Checks if row elements add upto 1, else returns false
if (sum != 1.0)
return false;
}
return true;
}
public static void main(String[] args) {
// Matrix to be checked
double mat[][] = {
{ 0.1, 0.5, 0.4 },
{ 0, 0.5, 0.5 },
{ 0.9, 0, 0.1 },
};
// Print results
if (markovMatCheck(mat))
System.out.println("The matrix is a Markov matrix.");
else
System.out.println("The matrix is not a Markov matrix.");
}
}
輸出
The matrix is a Markov matrix.
方法 2:使用矩陣的動態初始化
在這種方法中,我們要求使用者輸入他們所需大小的矩陣,然後使用 for 迴圈計算每一行的和並檢查它是否加起來等於 1。
示例
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Enter number of matrix rows-");
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int mat[][] = new int[size][size];
// Enter Matrix Elements
System.out.println("Enter the matrix elements");
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat.length; j++) {
mat[i][j] = sc.nextInt();
}
}
// Print results
if (markovMatCheck(mat))
System.out.println("The matrix is a Markov matrix.");
else
System.out.println("The matrix is not a Markov matrix.");
}
//user defined method
static boolean markovMatCheck(int mat[][]) {
int sum = 0;
// Traverses the matrix
for (int i = 0; i < mat.length; i++) {
sum = 0;
// Adds the row elements
for (int j = 0; j < mat.length; j++) {
sum += mat[i][j];
}
// Checks if row elements add upto 1, else returns false
if (sum != 1)
return false;
}
return true;
}
}
輸出
Enter number of matrix rows- 3 Enter the matrix elements 1 0 0 0 1 0 0 0 1 The matrix is a Markov matrix.
在這篇文章中,我們探討了使用 Java 程式語言檢查矩陣是否為馬爾可夫矩陣的不同方法。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP