Random but not more than 3 times the same draw in a row

Dear all,
I need to display 2 stimuli side by side on a screen, but in random positions (left or right).
To do this, I firstly created a simple 2 values vector (posx) within a Shuffle function, giving the center positions of both my stimuli on the x axis

posx=Shuffle([.25 .75]) 

squareXpos1 = round([screenXpixels * posx(1)])
squareXpos2 = round([screenXpixels * posx(2)])

But now, for learning matters, I need the stimuli to never appear in the same order more than 3 times in a row. This is all included in a for loop (i=1:20)

I came to this solution, but I don’t think this is the easiest way to do it…

for i=1:20

	if i>3
	    if eval(['posx' num2str(i-1) '==[.25 .75]']) & eval(['posx' num2str(i-2) '==[.25 .75]']) & eval(['posx' num2str(i-3) '==[.25 .75]'])
	        eval(['posx' num2str(i) '=[.75 .25]'])
	    elseif eval(['posx' num2str(i-1) '==[.75 .25]']) & eval(['posx' num2str(i-2) '==[.75 .25]']) & eval(['posx' num2str(i-3) '==[.75 .25]'])
	        eval(['posx' num2str(i) '=[.25 .75]'])        
	    else
	        eval(['posx' num2str(i) '=Shuffle([.25 .75])'])
	    end
	else
	    eval(['posx' num2str(i) '=Shuffle([.25 .75])'])
	end    

    squareXpos1 = round([screenXpixels * eval(['posx' num2str(i) '(1)'])]);
    squareXpos2 = round([screenXpixels * eval(['posx' num2str(i) '(2)'])]);

end

Does anyone have a better idea ? Or could teach me a simple way to tell matlab to change the order of the posx values in the “i” trial depending on the “i-1”, “i-2” and “i-3” posx values ?

Thank you all ! :grin:

It is simpler to generate one vector of 20 values, one element at a time. For each element you generate, check if it meets your requirements. If it does, add it to the vector. If it does not, regenerate. Oops, i mean array, not vector, in matlab langauge