s2015
s2015

Reputation: 37

How to fix a randomly generated sample in Matlab after making some changes to the code

I need to have the same sample (same data points) that was generated from a large set of data in order to make some comparisons as I vary some conditions or parameters. However, the sample changes after each Matlab run. My current sampling is based on the use of "randperm" or sampling without replacement.

Any help would e greatly appreciated. Thanks.

Upvotes: 1

Views: 34

Answers (2)

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

As pointed out by @Ander you can enforce reproducible randomness with rng.

However, if you sampled your data once and need to reuse the result of that multiple times, you probably don't want to keep generating it over and over again. In that case you would just want to store it.

If you are just using all your code in 1 go, you can assign it to a variable (like so: r = randperm(5)) and then call r each time when you need it. However I suspect that you are already doing this, and are in fact looking for something like this:

save r 

Which you can folluw up tomorrow with

load r

To get exactly the same variable which can be used directly.

Upvotes: 2

Ander Biguri
Ander Biguri

Reputation: 35525

You can set up the random sample generation seed with rng().

Example

for ii=1:10
   rng(1);
   randperm(5)
end

Upvotes: 3

Related Questions