MATLAB: How do you increment and continue until the end of all your experiments

cardsdeck of cardsdiscrete mathmonte carloprobability

Hello, I'm very new to matlab and have a question about my code. What I'm trying to do is find the average number of turns before an ace appears. I created an Array Deck and each turn would "draw" a random number from the array which represents a card. 1,14,27,40 represents the ACEs. Every time an ace is drawn it stops my "if-else" loop but I'm trying to run the experiment 1000 time to get a stable average. But the experiments stops once it finds the ACE. How would I increment the loop and have it start again until 1000 experiments is finish.
my code:
N=1000;
turns=0;
ace = 0;
for experiments = 1:N %run the for loop up to 1000;
deck = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52];
msize = numel(deck);
card = deck(randperm(msize,1));
if (card == 1)||(card == 14)||(card == 27)||(card == 40)
ace=ace+1;
fprintf('we got an ACE at turn: %d\n ',turns+1)
return %ends the loop
else
turns = turns+1;
fprintf('turns: %d\n', turns);
end
end

Best Answer

You can simplify a lot your code. Try this
N=100;
aces = [1,14,27,40];
first_ace_n = zeros(1,N);
for k=1:N
%a random stack of 52 cards
deck = randperm(52);
%find where all aces are
[C,ix_deck,ix_aces]=intersect(deck,aces);
%number of card to find the first ace
first_ace_n(k) = min(ix_deck);
fprintf('We got first ace at card: %d \n',first_ace_n(k));
end
mean_card_n = mean(first_ace_n)
Last line gives you the mean number of cards to find the first ace.
Related Question