MATLAB: How to mix two arrays with constraints

arraysconstraints

Hi, I got stuck on a question and would be grateful if you could help. I would like to randomly interleave 2 arrays with 2 constraints.
1- I have two arrays that I will be interleaving with each other. Each array has elements repeated 4 times.
ConditionA = repmat(1:20,1,4) % Array 1
ConditionB = repmat(21:40, 1,4) % Array 2
WholeArray = [ConditionA ConditionB];
% I randomize the presentation order first by
randArr = randperm(length(WholeArray))
for i = 1: length(WholeArray)
randArray(i) = WholeArray(randArr(i));
end
2- Now, I'd like to apply my two constraints. Constraint 1: Do not have more than 2 consecutive numbers from the same array (condition). So the array cannot go [… 19 18 15 …] because all of these three numbers belong to the Condition A array.
Constraint 2: Do not let two identical numbers consecutively follow each other and have at least two numbers in between such that the array cannot go […20 39 20 ..] because there is only 1 number that separates two identical numbers.
Thank you for reading this. If anyone could give me at least some guidelines about how to go about this, I would be grateful. Thanks, Melisa

Best Answer

I made some changes about setting your data at the beginning and now you have a code that performs what you want. Let me know the results.
ConditionA = repmat([1:20].',4,1); % Array 1
ConditionB = repmat([21:40].',4,1); % Array 2
WholeArray = [ConditionA ConditionB];
% I randomize the presentation order first by
randArray=zeros(1,size(ConditionA,1));
while true
randArr = randperm(length(WholeArray));
for i = 1: length(WholeArray)
if mod(i,2)~=0%odd
randArray(i) = WholeArray(randArr(i),1);%take value from first column, ConditionA
else
randArray(i) = WholeArray(randArr(i),2);%take value from second column, ConditionB
end
end
j=1:numel(randArr)-2;
if sum(randArray(j)==randArray(j+2))~=0
else
break;
end
end