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