JavaScript Program for Markov Matrix

A matrix is a kind of 2-D array, which is in the form of some number of rows, and for each row, there is the same number of columns and by the row and column number, we can get the element at any particular index. For the Markov matrix, each row's sum must equal 1. We are going to implement a code to create a new Markov matrix and find if the currently given matrix is a Markov matrix or not.

What is a Markov Matrix?

A Markov matrix is a special type of matrix where each row represents probability distributions. The key property is that each row's elements sum to exactly 1, representing the total probability of 100%. These matrices are commonly used in probability theory and statistics.

Markov Matrix Example: 0.3 0.7 0.0 0.2 0.5 0.3 0.4 0.0 0.6 Row 1: 0.3 + 0.7 + 0.0 = 1.0 Row 2: 0.2 + 0.5 + 0.3 = 1.0 Row 3: 0.4 + 0.0 + 0.6 = 1.0

Creating a Binary Markov Matrix

In this implementation, we create a special case of Markov matrix using only binary digits (0 and 1). Each row will have exactly one '1' and the rest '0', ensuring the row sum equals 1.

Approach

We create a matrix where for each row, we randomly select one column to place a '1' and fill the remaining positions with '0'. This guarantees each row sums to exactly 1.

// Creating a binary Markov matrix
function createBinaryMarkovMatrix(rows, cols) {
    // Create array to hold the matrix
    var matrix = new Array(rows);
    
    // Process each row
    for (var i = 0; i < rows; i++) {
        // Create row array filled with zeros
        var row = new Array(cols);
        row.fill(0);
        
        // Generate random column index
        var randomCol = Math.floor(Math.random() * cols);
        
        // Set that position to 1
        row[randomCol] = 1;
        
        // Add row to matrix
        matrix[i] = row;
    }
    
    return matrix;
}

// Create and display a 4x5 binary Markov matrix
var rows = 4, cols = 5;
var binaryMarkov = createBinaryMarkovMatrix(rows, cols);

console.log("Binary Markov Matrix:");
for (var i = 0; i < binaryMarkov.length; i++) {
    console.log("Row " + (i+1) + ":", binaryMarkov[i]);
}
Binary Markov Matrix:
Row 1: [ 0, 1, 0, 0, 0 ]
Row 2: [ 0, 0, 0, 1, 0 ]
Row 3: [ 1, 0, 0, 0, 0 ]
Row 4: [ 0, 0, 1, 0, 0 ]

Checking if a Matrix is Markov

To verify if a given matrix is a Markov matrix, we need to check that each row's sum equals 1. We'll handle floating-point precision issues by checking if the sum is very close to 1.

function isMarkovMatrix(matrix) {
    var rows = matrix.length;
    var cols = matrix[0].length;
    
    // Check each row sum
    for (var i = 0; i < rows; i++) {
        var rowSum = 0;
        
        // Calculate sum of current row
        for (var j = 0; j < cols; j++) {
            rowSum += matrix[i][j];
        }
        
        // Check if sum is approximately 1 (handle floating point precision)
        if (Math.abs(rowSum - 1) > 0.001) {
            return false;
        }
    }
    
    return true;
}

// Test with valid Markov matrix
var validMatrix = [
    [0.3, 0.4, 0.3],
    [0.5, 0.25, 0.25],
    [1.0, 0.0, 0.0],
    [0.33, 0.34, 0.33]
];

console.log("Testing valid matrix:");
console.log("Is Markov matrix?", isMarkovMatrix(validMatrix));

// Test with invalid matrix
var invalidMatrix = [
    [0.5, 1.0, 0.5],  // Sum = 2.0 (invalid)
    [0.5, 0.25, 0.25],
    [1.0, 0.0, 0.0]
];

console.log("\nTesting invalid matrix:");
console.log("Is Markov matrix?", isMarkovMatrix(invalidMatrix));
Testing valid matrix:
Is Markov matrix? true

Testing invalid matrix:
Is Markov matrix? false

Complete Example with Row Sum Verification

function verifyMarkovMatrix(matrix, matrixName) {
    console.log("<br>" + matrixName + ":");
    
    var rows = matrix.length;
    var cols = matrix[0].length;
    var isValid = true;
    
    for (var i = 0; i < rows; i++) {
        var rowSum = 0;
        var rowStr = "Row " + (i + 1) + ": [";
        
        for (var j = 0; j < cols; j++) {
            rowSum += matrix[i][j];
            rowStr += matrix[i][j];
            if (j < cols - 1) rowStr += ", ";
        }
        
        rowStr += "] = " + rowSum.toFixed(2);
        console.log(rowStr);
        
        if (Math.abs(rowSum - 1) > 0.001) {
            isValid = false;
        }
    }
    
    console.log("Result: " + (isValid ? "Valid Markov Matrix" : "Invalid Markov Matrix"));
}

// Example matrices
var matrix1 = [
    [0.2, 0.3, 0.5],
    [0.4, 0.4, 0.2],
    [0.1, 0.6, 0.3]
];

var matrix2 = [
    [0.5, 0.3, 0.5],  // Invalid: sum = 1.3
    [0.4, 0.4, 0.2],
    [0.1, 0.6, 0.3]
];

verifyMarkovMatrix(matrix1, "Matrix 1");
verifyMarkovMatrix(matrix2, "Matrix 2");
Matrix 1:
Row 1: [0.2, 0.3, 0.5] = 1.00
Row 2: [0.4, 0.4, 0.2] = 1.00
Row 3: [0.1, 0.6, 0.3] = 1.00
Result: Valid Markov Matrix

Matrix 2:
Row 1: [0.5, 0.3, 0.5] = 1.30
Row 2: [0.4, 0.4, 0.2] = 1.00
Row 3: [0.1, 0.6, 0.3] = 1.00
Result: Invalid Markov Matrix

Time and Space Complexity

Operation Time Complexity Space Complexity
Create Binary Markov Matrix O(N × M) O(N × M)
Check if Matrix is Markov O(N × M) O(1)

Where N is the number of rows and M is the number of columns in the matrix.

Conclusion

Markov matrices are fundamental in probability theory where each row represents probability distributions summing to 1. We've implemented both creation and verification functions with proper floating-point handling for robust matrix validation.

Updated on: 2026-03-15T23:19:01+05:30

269 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements