MATLAB: How to save the RNG state for later reproducibility

recreate rngsave rng

I am trying to debug my code and want to save RNG seeds to a text file or some similar simple data storage, with the goal being that I can later review failed instances of the code using exactly the same RNG state which created them. Thanks.

Best Answer

Of course you can find such details in the documentation: doc rng
state = rng;
x = rand(1,5)
x =
0.8147 0.9058 0.1270 0.9134 0.6324
rng(state);
y = rand(1,5)
y =
0.8147 0.9058 0.1270 0.9134 0.6324
Storing the state in a text file is not trivial, because it is a struct. Prefer a MAT file using save and load:
File = fullfile(tempdir, 'RNGState.mat');
save(File, 'state');
...
Data = load(File);
state = Data.state;