Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program for Markov matrix in C++
Given a matrix M[r][c] with ‘r’ number of rows and ‘c’ number of columns, we have to check that the given matrix is Markov matrix or not. If the input matrix is Markov matrix then print the output “It is a Markov matrix” and “it’s not an Markov matrix” if it is not a Markov matrix.
Markov Matrix
Now, what is Markov Matrix? A matrix M is a Markov matrix if and only if its sum of each row is equal to only 1.
Like in the given example below −
$$\begin{bmatrix}0.2 & 0.3 & 0.5 \0.1 & 0.7 & 0.2 \0.4 & 0.5 & 0.1 \\end{bmatrix}\$$
In the above example if we sum each row −
1st row sum = 0.2+0.3+0.5 = 1.0 2nd row sum = 0.1+0.7+0.2 = 1.0 3rd row sum = 0.4+0.5+0.1 = 1.0
Here every row has a sum of 1.0, so the above matrix is Markov matrix.
Example
Input: m[][] = { {0.2, 0.3, 0.5} ,
{0.1, 0.7, 0.2},
{0.4, 0.5, 0.1}}
Output: It is a Markov matrix
Input: m[][] = { {0, 0, 1} ,
{0, 0.7, 0.3},
{0.5, 0.5, 0}}
Output: It is a Markov matrix
Approach
We will make another 1-d matrix and store the sum of every row in that matrix. Then we will iterate the whole array and then find whether all the elements in the array is 1 or not, if 1 then the given matrix was Markov matrix else the matrix is not Markov matrix
Algorithm
Start
Step 1 -> Define macro as #define n 3
Step 2 -> declare function to check for markov matrix
bool check(double arr[][n])
Loop For int i = 0 and i <n and i++
Declare double sum = 0
Loop For int j = 0 and j < n and j++
Set sum = sum + arr[i][j]
If (sum != 1)
return false
End
End
Return true
Step 3 -> In main ()
Declare double arr[3][3] = { { 0, 0, 1 },
{ 0.5, 0, 0.5 },
{ 0.9, 0, 0.1 } }
If (check(arr))
Print its a markov matrix
Else
Print its not a markov matrix
Stop
Example
#include <iostream>
using namespace std;
#define n 3
//check for markov matrix
bool check(double arr[][n]){
for (int i = 0; i <n; i++){
double sum = 0;
for (int j = 0; j < n; j++)
sum = sum + arr[i][j];
if (sum != 1)
return false;
}
return true;
}
int main(){
double arr[3][3] = { { 0, 0, 1 },
{ 0.5, 0, 0.5 },
{ 0.9, 0, 0.1 } };
if (check(arr))
cout << "its a markov matrix ";
else
cout << "its not a markov matrix ";
}
Output
its a markov matrix