# How to I iterate a random selection among given elements without selecting the same element twice?

3 views (last 30 days)
Kristin on 27 Apr 2022
Commented: Jan on 27 Apr 2022
Hello,
I am conducting an experiment and would like to present different stimuli (stimpair1 thru stimpair8) across 8 blocks (Nblocks = 8). The presented stimulus within each block shall be the same though. I would like to randomize the stimulus selection without selecting the same stimulus twice, such that a differerent stimulus is presented in every block. I have already randomized stimulus selection using the following code.
stimlist = [list.stimpair1; list.stimpair2; list.stimpair3; list.stimpair4; list.stimpair5; list.stimpair6; list.stimpair7; list.stimpair8];
for bnum = 1:Nblocks
stimpairpresented = [];
stimpairpresented = [stimpairpresented,randi(8)];
switch stimpairpresented
case 1
chosenstim.s1 = list.stimpair1
case 2
chosenstim.s2 = list.stimpair2
case 3
chosenstim.s3 = list.stimpair3
case 4
chosenstim.s4 = list.stimpair4
case 5
chosenstim.s5 = list.stimpair5
case 6
chosenstim.s6 = list.stimpair6
case 7
chosenstim.s7 = list.stimpair7
otherwise
chosenstim.s8 = list.stimpair8;
end
end
Yet, I am stuck at how to implement the condition that the presented stimulus is not the same as one that was presented in the previous blocks. Can someone help me with that?
Best

Jan on 27 Apr 2022
By the way, your code wouzld be much cleaner and shorter, if you use arrays instead of hiding indices in the field names: Define list.stimpair as nan(1, NBlock) and your code becomes:
for bnum = 1:Nblocks
index = randi(8);
chosenstim.s(index) = list.stimpair(index);
end
To avoid repetition use randperm:
index = randperm(8, 8)
chosenstim.s(index) = list.stimpair(index);
No loop, no switch, no bunch of case blocks, and even:
stimlist = [list.stimpair1; list.stimpair2; list.stimpair3; list.stimpair4; list.stimpair5; list.stimpair6; list.stimpair7; list.stimpair8];
becomes:
stimlist = list.stimpair;
Do you see the power of arrays instead of numbered field names?
A hint:
stimpairpresented = [];
stimpairpresented = [stimpairpresented,randi(8)];
% is exactly the same as:
stimpairpresented = randi(8);
##### 2 CommentsShowHide 1 older comment
Jan on 27 Apr 2022
I used nan(1, NBlock) as an example of how to create a vector with 8 elements.
If the used data contain 2 elements, you can store them in a matrix.
Currently it is not clear, what your input data are and what you want to achieve. Maybe this example helps:
stimuli = [1, 2; ...
3, 4; ...
5, 6; ...
7, 8; ...
9, 10];
mixedStimuli = stimuli(randperm(5), :)
mixedStimuli = 5×2
7 8 9 10 3 4 1 2 5 6