//------------------------------------------------------------------- // markov.cpp // // This program shows the transition matrix and a sequence of // the state vectors for a Markov Chain with prescribed data. // // to compile: $ g++ markov.cpp -o markov // to execute: $ ./markov // // programmer: ALLAN CRUSE // written on: 01 MAR 2011 //------------------------------------------------------------------- #include // for printf() #include // for memcpy() #define N_STATES 2 // number of states #define N_STEPS 13 // number of steps typedef double Vector[ N_STATES ]; typedef double Matrix[ N_STATES ][ N_STATES ]; Vector initial = { .50, .50 }; Matrix transition = { .8, .2, .3, .7 }; int main( int argc, char **argv ) { // display the transition matrix printf( "\n The Markov Chain Transition Matrix: " ); for (int i = 0; i < N_STATES; i++) { printf( "\n " ); for (int j = 0; j < N_STATES; j++) printf( " %1.4f ", transition[ i ][ j ] ); } printf( "\n\n" ); // display the sequence of state vectors Vector current; memcpy( current, initial, sizeof( current ) ); for (int step = 0; step < N_STEPS; step++) { // display the current state vector printf( " State Vector %-4d ", step ); for (int j = 0; j < N_STATES; j++) printf( " %1.4f ", current[ j ] ); printf( "\n\n" ); // compute the next state vector Vector product; for (int j = 0; j < N_STATES; j++) { double sum = 0.0; for (int k = 0; k < N_STATES; k++) sum += current[ k ] * transition[ k ][ j ]; product[ j ] = sum; } memcpy( current, product, sizeof( current ) ); } }