Hello fellow Matlab users!
I have been working on an experiment, in which two conditions have to appear an equal number of times while being (pseudo)randomized. This proved to be quite challenging, so if you can help I would be be very glad:
I have two possible conditions (0 or 1) in an X long vector that I want to permute. However, each condition can only appear Z times in a row and both conditions have to appear an equal number of times.
I tried to use some lines of code that I found on another post:
(https://uk.mathworks.com/matlabcentral/answers/112353-shuffle-vector-with-constraints?s_tid=answers_rc1-1_p1_MLT)
seq = str2double(seq);seq = seq(randperm(numel(seq))); %initial shuffle
old_idx = unique(find(diff(seq)==0)); %find repeats
while ~isempty(old_idx) %continue until no repeats
new_idx = unique(setdiff([1:length(seq)],old_idx)); %find new spots
new_idx = new_idx((randi(length(new_idx),length(old_idx),1)))'; seq([new_idx; old_idx],:) = seq([old_idx;new_idx],:); %swap
old_idx = unique(find(diff(seq)==0)); %find repeatsend
Now… in theory it works!
But the shuffling process can take very long and in some cases it appears to be stuck.
The code was written for vectors of number sequences [1:9] which might not be ideal in the case of a dichotomous variable such as condition 1 vs 2, as there might be many more repetitions. Also it draws from the same index variable which might create more repetitions.
Often it is stuck because there are no counterparts to draw from: e.g. there are say four "zeros" in a row but no "ones" to swap with.
I tried some other strategies, where I just reshuffle the whole vector if some conditions are met. But this is not just awkward to write and read, it is als computationally slow and has the same problem of being stuck at one point.
The other mothod is doing it once by hand and then stick with that pseudorandomization, which in psychological experiments is more or less common practice. But I don't know the number of trials and items yet, so it would be nice to automatize this; and also because I will have to do this again in a different part of the experiment.
What you would do in this case?
Best Answer