Reputation: 883
Okay, this is like the 5th time I have had to ask this question, and still nobody has been able to give me an answer or solution. But here we go again ...
I want to run a very simple little MATLAB program. All it does is RANDOMLY display images from a directory. Here is my code:
files = dir(fullfile(matlabroot,'toolbox','semjudge',bpic,'*.png'));
nFiles = numel(files);
combos = nchoosek(1:nFiles, 2);
index = combos(randperm(size(combos, 1)), :);
picture1 = files(index(nRep,1)).name;
picture2 = files(index(nRep,2)).name;
image1 = fullfile(matlabroot,'toolbox','semjudge',bpic,picture1);
image2 = fullfile(matlabroot,'toolbox','semjudge',bpic,picture2);
subplot(1,2,1); imshow(image1);
subplot(1,2,2); imshow(image2);
I have tried several different iterations of this, including replacing "nchoosek" with "randsample."
But it doesn't work! Every time I run the program, the script runs the same image files in the same order. Why is it doing this? It's like it randomized the image files the first time I ran it, but now it only runs them in that order, instead of randomizing them every time the script is run.
Can somebody please help me with this?
Upvotes: 0
Views: 482
Reputation: 15996
As an elaboration of @ypnos's answer, you probably want to add a line like this:
rng('shuffle');
To the start of your code. That will seed the random number generator with a value based on the time, and then you should get a different sequence of random numbers.
Upvotes: 5
Reputation: 52357
The pseudo-random number generator starts off from a specific seed. The "random" numbers provided are deterministic. You need to change the seed to change these numbers.
The benefit of this is that even if you use pseudo-randomness in your algorithm, you can always replay a run by using the same seed again.
Reference: http://www.mathworks.de/help/techdoc/ref/rng.html
Upvotes: 6