How can I simulate this code with 1000 simulations?

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 个评论

hello
P is not defined - cannot run your code
What is the point of mu having 10 entries? the cumsum will be 1 by the 4th, and rand() cannot exceed 1.
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.
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 个)

类别

帮助中心File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by