0

Suppose that we have two m-files :

First one is a function :

function XX = ofx()

for i=1:2
    aa = randperm(5)
end

end

Second one :

rng(0);
for i=1:2
   xx = randperm(3)
end

ofx();

You can see that when we run second code again and again the outputs is the same. Why we have these same outputs in both randperm? I only want same random generator for xx random numbers not ofx function. How can i do that? How can i only use rng for a specific function?

Thanks.

1 Answer 1

1

The problem is not the function. The problem is that you want a repeatable sequence of numbers for some uses of the RNG, and non-repeating for other uses. To do this, you need to carefully control the state of the RNG. I would reverse the way you think about them, and have your repeatable case save, then restore the state.

rng_state = rng(0);     % Save (pseudo-) random state of RNG, then seed with known value
for i=1:2
    xx = randperm(3);
end
rng(rng_state);         % Restore saved state so other RNG calls work as expected

ofx();
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for answer. Can we reset rng to default values likes we didn't use it? Can we return MATLAB random generator to default not previous condition rng_state?
Running help rng shows this possibility: rng('default'). You could also use rng('shuffle') to "re-randomize" the rng.

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.