Answer the question
In order to leave comments, you need to log in
How to implement an additional condition?
Add. condition: The traveler does not return to the city that he has visited most often in the last 10 days. In other cities - equally likely.
Calculate the stationary distribution by simulation.
Description of the variables used
P – Initial matrix
days – Number of days
starCity – Starting city
nowCity – City in which the traveler is currently located
сount – Cities visited count
P1 – Traveler's probability of being in the first city
P2 - Traveler's probability of being in the second city
P3 - Traveler's probability to be in the third city
P4 - Probability of the traveler to be in the fourth city
sum - The sum of the elements of the matrix
i - Counter
j - Counter
k - Counter
Program listing:
clear all
clc
days = 30; %количество дней
start = 2; %начальный город
Exp = 30; %количество экспериментов
P=[
0.1967 0.0750 0.2239 0.5044;
0.4561 0.0553 0.4863 0.0023;
0.3321 0.1986 0.0291 0.4402;
0.2982 0.0325 0.3382 0.3311;
]; %исходная матрица
count = [0 0 0 0]; %счётчик посещения городов
VerNow = zeros(1,4); %вероятн. нахожд. для всех городов в данный день
City = zeros(days,1); %города в которых побывал путешественник
VerNow(start) = 1;
City(1) = start;
MatRez = zeros(days,4); %матрица вероятностей
MatRez(1,:) = VerNow; %добавление текущего дня к последующему
for j = 2:1:days
VerNow = VerNow * P;
MatRez(j,:) = VerNow;
end;
disp(MatRez) %вывод матрицы вероятности
[p1,p2,p3,p4] = solve(...
'p1 = p1*0.1967 + p2*0.4561 + p3*0.3321 + p4*0.2982',...
'p2 = p1*0.0750 + p2*0.0553 + p3*0.1986 + p4*0.0325',...
'p3 = p1*0.2239 + p2*0.4863 + p3*0.0291 + p4*0.3382',...
'p4 = p1*0.5044 + p2*0.0023 + p3*0.4402 + p4*0.3311',...
'p1 + p2 + p3 + p4 = 1');
p1 = double(p1);
p2 = double(p2);
p3 = double(p3);
p4 = double(p4);
gran = zeros(4); %матрица сложения вероятностей
for i = 1:1:4
s = 0;
for j = 1:1:4
s = s+P(i,j);
gran(i,j) = s; %матрица по допустимым границам
end;
end;
for k = 1:1:Exp
%получение пути исходя из табл. вероятности
for i = 2:1:days
perehod = rand(); %вероятность перейти в другой город
NowCity = City(i-1);
if(perehod <= gran(NowCity,1))
City(i) = 1;
end;
if(perehod > gran(NowCity,1) && perehod <= gran(NowCity,2))
City(i) = 2;
end;
if(perehod > gran(NowCity,2) && perehod <= gran(NowCity,3))
City(i) = 3;
end;
if(perehod > gran(NowCity,3) && perehod <= gran(NowCity,4))
City(i) = 4;
end;
end;
if((k == 10) || (k == 50) || (k == 100))
figure
stairs (City);
axis([0 10 0 5])
end;
%считаем количество городов, в которых останавливался путешественник
%на последний день с учетом количества проведенных экспериментов
count(City(days)) = count(City(days)) + 1;
end;
figure
bar(count/Exp,0.1); %вычисление стационарного состояния
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question