1

I am trying to generate a matrix with some error but it should be different every trail.But in my case,I am getting exactly same matrix with error on each trail.My code is below-

N=50;
R=50;
TrialNum=100;
Error,Pe=0.05;

A(1:N,1:N) = eye(N); 

seed=6; 
rng(seed,'twister');
B = round((rand(R,N)));

C=[A;B];

for t=1 : TrialNum
    Rp = C ;
    for i=1:(N+R)
        if(rand < Pe)   
            Rp(i,:) = 0;
        end
    end
end

From this code, every time I will get A as diagonal matrix and B will generate matrix using random number with seed. C is total 100x50 matrix.This matrix will goes to next loop and every trail different number of packet will be lost due to Pe.

C matrix will be same all the trail but Rp matrix will be different for every trial but I am getting exactly same Rp matrix on every trail.

For example-

trial=1, N=3, R=2
Rp=1 0 0 
   0 1 0 
   0 0 0 
   1 0 1
   0 1 1 

trial=2, N=3, R=2
Rp=1 0 0 
   0 0 0 
   0 0 1 
   1 0 1
   0 0 0

Need some experts comment.Any help will be appreciated.

1 Answer 1

1

The problem is, since you use the same seed every time, Matlab's random number generator is generating the same realization of random numbers every time you run your program.

Instead of using rng with a seed, you should use no seed and call

rng('shuffle')

once before calling the subsequent rand functions to generate the random matrix, and the random numbers in your loop.

In other words modify your code to

rng('shuffle')
B = round((rand(R,N)));

    C=[A;B];

    for t=1 : TrialNum
        Rp = C ;
        for i=1:(N+R)
            if(rand < Pe)   
                Rp(i,:) = 0;
            end
        end
    end

You will get different realizations of random numbers for different runs of your Matlab program because the seed will be set by Matlab based on the system clock if you use shuffle.

Now, if you want the B matrix to be repeatable, but the random numbers in the loop to be different you could do

seed=6; 
rng(seed,'twister');
B = round((rand(R,N)));

C=[A;B];

followed by

rng('shuffle')
for t=1 : TrialNum
    Rp = C ;
    for i=1:(N+R)
      if(rand < Pe)   
         Rp(i,:) = 0;
       end
    end
end
Sign up to request clarification or add additional context in comments.

3 Comments

paisanco thanks for your answer but I want to control my random number using seed. I do not want to control rand for the second loop rather I want B matrix will be same all time but Rp will be different.
In that case you should be able to call with a seed as before while generating the B matrix, then recall rng('shuffle') after so your Rp's are different between runs.
Happy to help best of luck.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.