MATLAB: Create a pseudo-random array with a set probability of similarity to an existing random array

dependent arrayprobabilitypseudorandomrandirandom

I have created a random array of 32 trials each presenting a stimuli associated with a number 1-4. I want to make a second array also of numbers 1-4 where in 50% of the trials, the value in the second array equals the value in the first array. I also want to make sure that each stimuli (1-4) is being shown roughly the same number of times, i.e. if 16 trials have the same number in each array, 4 of them are stimuli 1, 4 are stimuli 2, 4 are stimuli 3, and 4 are stimuli 4. The other 16 trials do not have the same value in both arrays.
My code for the first array is
array1 = randi([1 4], 1, 32);
I am want array2(ii) == array1(ii) for 50% of the trials.
Thanks!

Best Answer

With such constrained stimulus pairs it might be more straight-forward to generate exactly the pairs you want systematically and then randomize their order at the end, maybe like this:
matches4 = [1 1; 2 2; 3 3; 4 4];
matches16 = repmat(matches4,4,1); % Here are the 16 match trials.
nonmatches12 = [1 2; 1 3; 1 4; 2 1; 2 3; 2 4; 3 1; 3 2; 3 4; 4 1; 4 2; 4 3]; % 12 possible nonmatches
% Now make 4 extra nonmatches so that you will have sixteen total:
nonmatches4 = [1 2; 3 4; 4 1; 2 3]; % Not entirely sure which nonmatches you want to repeat.
stimuli = [matches16; nonmatches12; nonmatches4]; % stimulus pairs for 32 trials
stimuli = stimuli(randperm(size(stimuli, 1)), :); % randomize the order of the stimulus pairs