One-time randomization

2019-03-05 11:07发布

问题:

I have a matrix, ECGsig, with each row containing a 1-second-long ECG signal,

I will classify them later but I want to randomly change the rows like,

idx = randperm(size(ECGsig,1));
ECGsig = ECGsig(idx,:);

However I want this to happen just once and not every time that I run the program,

Or in other words to have the random numbers generated only once,

Because if it changes every time I would have different results for classification,

Is there any way to do this beside doing in a separate m file and saving it in a mat file?

Thanks,

回答1:

You can set the random generation seed so that every time you run a random result, it will generate the same random result each time. You can do this through rng. This way, even though run the program multiple times, it will still generate the same random sequence regardless. As such, try doing something like:

rng(1234);

The input into rng would be the seed. However, as per Luis Mendo's comment, rng is only available with newer versions of MATLAB. Should rng not be available with your distribution of MATLAB, do this instead:

rand('seed', 1234);

You can also take a look at randstream, but that's a bit too advanced so let's not look at it right now. To reset the seed to what it was before you opened MATLAB, choose a seed of 0. Therefore:

rng(0); %// or
rand('seed', 0);

By calling this, any random results you generate from this point will be based on a pre-determined order. The seed can be any integer you want really, but use something that you'll remember. Place this at the very beginning of your code before you do anything. The main reason why we have control over how random numbers are generated is because this encourages the production of reproducible results and research. This way, other people can generate the results you have created should you decide to do anything with random or randomizing.

Even though you said you only want to run this randomization once, this will save you the headache of saving your results to a different file before you run the program multiple times. By setting the seed, even though you're running the program multiple times, you're guaranteed to generate the same random sequence each time.