Elif Y
Elif Y

Reputation: 251

Why the number is not randomized using Matlab

I am trying to write a Matlab code to simulate a dice and compute its mean and standard deviation.

The problem is that no matter how many times we run this code, the result of randi(6) keeps the same. It made me crazy.

n=20;
m=0;
c=0;

for i=1:10000

    while m<n
    x=randi(6);
    c=c+1;
    m=m+x;
    end

    M(i)=m;
    count(i)=c;
    diff(i)=M(i)-n;
end

Upvotes: 0

Views: 32

Answers (2)

rayryeng
rayryeng

Reputation: 104503

You forgot to reset m and c back to 0 once the while loop terminates. m is set to 0 outside of the for loop only once, and so when m finally surpasses n, m never changes. As such, simply set m = 0 in your for loop before the while loop happens. You also need to set c to 0 because you want to count events each time the for loop iterates.

I'm also not sure how you could think that diff(i) = 2.5 for all i. This difference is a probabilistic value. Also, I don't see how you could get a floating point number in the difference because you are generating integers and accumulating integers for each trial. I think you need to examine what this value should be.

So:

n=20;
%//m=0;
%//c=0;

for i=1:10000
    m = 0; %// Change here
    c = 0; %// Change here too
    while m<n
    x=randi(6);
    c=c+1;
    m=m+x;
    end

    M(i)=m;
    count(i)=c;
    diff(i)=M(i)-n;
end

Upvotes: 0

user1980812
user1980812

Reputation: 81

I think you forgot to set m back to ZERO at the end of the for. If you want the sequence of randi to change you should take a look at the function "rng".

n=20;
m=0;
c=1;

for i=1:100

    while m<n
        x(i, c)=randi(6);
        m=m+x(i,c);
        c=c+1;
    end

    M(i)=m;
    count(i)=c;
    diff(i)=M(i)-n;
    m = 0;
end

Upvotes: 1

Related Questions