How to set a global random seed in a GUI?

5 views (last 30 days)
Can you just do something like handles.rng('default') and then handles.rng(1) to initialize a seed and reinitialize the same seed later in the code?
Not sure how to go about this. I need a global random seed that I can reinitialize (with the same seed) in different callback functions (and functions called within callback functions).

Accepted Answer

Adam Danz
Adam Danz on 30 Nov 2019
Edited: Adam Danz on 30 Nov 2019
You're on the right track. Choose a random seed when the GUI initializes and store it in your GUI using guidata() so all components have access to it and can reseed it whenever necessary.
Here's a demo. Based on your examples, I'm assuming you're not using app designer.
% At the end of the GUI opening function
function myOpeningFcn(hObject, . . .)
. . .
handles.rngSeed = randi(2^32 - 1);
guidata(hObject, handles);
end
% Some callback function
function myCallbackFcn(. . ., handles)
. . .
rng(handles.rngSeed)
end
Another good idea would be to add the following line to your closereq function so that your rng seed is randomized again.
rng shuffle
  3 Comments
Adam Danz
Adam Danz on 30 Nov 2019
Edited: Adam Danz on 13 Jan 2020
randi(2^32-1) merely chooses a random seed. Seeds are positive integers that must be less than or equal to that number in randi().
Once you have chosen a random integer, that value will be available anywhere in your code to be re-seeded using rng(). If you wanted to re-seed when you open the gui, you could run that line if your comment above. I was under the impression that you'd like to re-seed with the same value at different places in your GUI.
Ajay Peddada
Ajay Peddada on 30 Nov 2019
I see. To clarify - I will always be able to sample from the same “random” distribution in any matlab session as long as I seed the generator with the positive integer each time?

Sign in to comment.

More Answers (0)

Categories

Find more on Interactive Control and Callbacks in Help Center and File Exchange

Products


Release

R2013b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!