Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(In Java) An n X n matrix is called a positive Markov matrix if each element is

ID: 3569650 • Letter: #

Question

(In Java) An n X n matrix is called a positive Markov matrix if each element is positive and the sum of the elements in each column is 1. Write the following method to check whether a matrix is a Markov matrix.

public static boolean isMarkovMatrix(double[][] m)

Write a test program that prompts the user to enter a 3 X 3 matrix of double values and tests whether it is a Markov matrix.

Sample run:

Enter a 3-by-3 matrix row by row:

0.15 0.875 0.375

0.55 0.005 0.225

0.30 0.12 0.4

It is a Markov matrix

Explanation / Answer


import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
public static boolean isMarkovMatrix(double[][] m)
{

   for(int i=0; i<3; i++)
   {
double sum=0;
       for(int j=0; j<3; j++)
       {

if(m[j][i] <0)
   return false;
           sum+= m[j][i];

       }
if(sum != 1.0)
return false;
   }

return true;
}

   public static void main (String[] args) throws java.lang.Exception
   {

double[][] m = new double[3][3];

System.out.println("Enter a 3-by-3 matrix row by row: ");
Scanner in = new Scanner(System.in);
       for(int i=0; i<3; i++)
   {
       for(int j=0; j<3; j++)
       {
           m[i][j]=in.nextDouble();
       }
   }

if(isMarkovMatrix(m))
System.out.println("It is a Markov matrix");
else
System.out.println("It is NOT a Markov matrix");
   }
}