"Roger Stafford" wrote in message <je8a4o$p5m$1@newscl01ah.mathworks.com>...
> "Norm" wrote in message <je6k08$pbo$1@newscl01ah.mathworks.com>...
> > I'm new to Matlab and need to randomise some stimuli for an experiment. I have 25 images which need to be shown in two alternating conditions without the same image being shown twice in a row. What is the simplist way to do this?
>         
> This may not be the simplest way to do this but at least it gives an answer.
>
> n = 25;
> p1 = 1:n+1;
> p2 = zeros(1,n);
> m = 0;
> while m == 0
> b1 = [true(1,n),false];
> b2 = [false,false,true(1,n1)];
> for k = 1:n
> b = b1 & b2;
> m = sum(b);
> if m==0, break, end
> a = p1(b);
> r = a(ceil(m*rand));
> p2(k) = r;
> b1(r) = false;
> b2 = b2([n+1,1:n]);
> end
> end
> q = randperm(n);
> p1 = q(p1(1:n));
> p2 = q(p2);
>
> The indices in p1 and p2 each represent a distinct permutation of the 25 images with the p1 being those with the first "condition" and p2 the second. The indices in p1 and p2 are to be used alternately with the first element of p1 first, the first element of p2 second, the second element of p1 third, etc. until all 25 images have been used with each condition.
>
> Probably you will want to write something like:
>
> p = reshape([p1;p2],1,[]);
>
> where p gives 50 successive image indices, each of the 25 used twice, with the condition understood to alternate. No consecutive pairs should be alike.
>
> I was unable to think of a way to make all different possible arrangements have the same theoretical probabilities, nor to insure that every first try would always succeed. However the above whileloop only fails on its first trip about once every 20 or 30 times, and the probability differences are likely too subtle to be noticed unless n is very much smaller than 25, so perhaps you will be content with this.
>
> Roger Stafford
       
I am chagrined to find that the following more crude method of trying repeatedly to pair one random permutation with another and rejecting the failures should be considerable faster statistically in matlab (at least for n = 25) than my earlier more careful one in this thread, even though this one requires many more tries through the whileloop on average to achieve success. You would be advised to use this more crude method. Also it is guaranteed to choose permutation pairs equally among all those possible.
n = 25;
p1 = randperm(n);
b = true;
while b % Keep trying until an acceptable p2 shows up
p2 = randperm(n);
b = any(p1==p2)  any(p1(2:n)=p2(1:n1)); % Rejection criterion
end
p = reshape([p1;p2],1,[]);
Roger Stafford
