How can I simulate this code with 1000 simulations?

4 次查看(过去 30 天)
If I run a chain of n = 50 with four states, then how can I adjust the following code to run for 1000 times.
% I want to run this code 1000 times?
n = 50; % length of the chain
X = zeros(n,1); % matrix to save the chain in future
mu = [1/4 1/4 1/4 1/4]; % initial position of the chain
P = [0 1/2 0 1/2; 1/2 0 1/2 0; 0 1/2 0 1/2; 1/2 0 1/2 0]; % probability transition matrix
U = rand; % generate a random number
X_0 = min(find(U <= cumsum(mu))); % get the next state
U = rand;
X(1) = min(find(U <= cumsum(P(X_0,:))));
% do this process for the entire length (n) of the chain
for i = 1:n-1
U = rand;
X(i + 1) = min(find(U <= cumsum(P(X(i),:))));
end
How can I run this chain e.g. 1000 times
The above code is just an example, in practice, I have P = cell array. It is difficult to provide the whole data here thats why I tried to come up with a small example.
I tried to do something like this that but it did not work.
n = 50; % length of the chain
simulations = 1000
X = zeros(n,simulations); % matrix to save the chain in future
mu = [1/4 1/4 1/4 1/4]; % initial position of the chain
P = [0 1/2 0 1/2; 1/2 0 1/2 0; 0 1/2 0 1/2; 1/2 0 1/2 0]; % probability transition matrix
for k = 1:simulations
U = rand(1,m); % generate a random number
X_0 = min(find(U <= cumsum(mu),2)); % get the next state
U = rand(1,m);
X(1,m) = min(find(U <= cumsum(P(X_0,:))));
% do this process for the entire length (n) of the chain
for i = 1:n-1
U = rand;
X(i + 1) = min(find(U <= cumsum(P(X(i),:))));
end
end
  4 个评论
susman
susman 2021-2-26
I have just rephrased the questions. I tried to provide the small example to understand how does the code work. If its still not clear, I would try to rephrase agaib. Really sorry for that.
Walter Roberson
Walter Roberson 2021-3-2
What is m? You have
U = rand(1,m);
X(1,m) = min(find(U <= cumsum(P(X_0,:))));
Your U is going to be a row vector, but P(X_0,:) is going to be a row vector, so you have <= between a row vector and a column vector, which is going to get you an m by size(P,2) -> m x 4 array. But then you try to store that into the scalar location X(1,m)

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Splines 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by