How can I randomly extract a element in an array?

3 views (last 30 days)
If now I have an array, how can I randomly extract a element in it? x0_1 = [ 0 0 0 1 1 1 2 2 2 2 ];
Actually, I want to prove the limiting distribution of Markov chain by Matlab and I was given a initial probability P(X0 = 0) = 0.3, P(X0 = 1) = 0.3, P(X0 = 2) = 0.4.
Professor tells us to use the probability above to extract the first one state and if I get the state1, just follow the probability of state1 in transition probability matrix to get the next state but I am not very sure how to do ...
Hope you can tell me how to randomly extract a element in the vector. Thanks!

Accepted Answer

mounika
mounika on 11 Nov 2017
If it is just about how to extract an element randomly, you can try by random indexing, you can try the following for the given vector:
x = [0 0 0 1 1 1 2 2 2 2];
len = length(x);
for i = 1:length(x)
y = randi([1 len],1,1); % generates random number for indexing
disp(x(y));
end

More Answers (0)

Community Treasure Hunt

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

Start Hunting!