MATLAB: Common random number when satisfying certain conditions

indicesrandom numberrepeat

Hi all,
I'm trying to generate a matrix of random numbers that has to satisfy the restriction that when certain conditions are satisfied, the random numbers must be the same. Consider the following example with two individuals (id takes the values 1 and 2) and up to six options (defined by ch)
id=[1 1 1 1 1 1 2 2 2 2 2 2]';
ch=[1 2 3 1 2 3 3 4 5 3 5 6]';
I would like to generate random numbers such that whenever id==i and ch==j, the numbers are the same (and the same is true for all values of i and j).
I was able to do this in the following way
RN=zeros(12,5);
U=unique(id);J=unique(ch);
RNo=randn(kron(max(size(U)),max(size(J))),5); %for each combination I need 5 random numbers. Note that this generates random numbers that will never be used because there are some combinations of id and ch that do not appear in the data.
DJ=repmat(J,max(U),1); % Define a vector with all possible alternatives
DI=kron(U,ones(max(J),1)); % Define a vector with id repeated as many times as possible alternatives
for k=1:max(size(id))
ii=id(k,1);jj=ch(k,1);
for s=1:5,
RN(id==ii & ch==jj,s)=RNo(DI==ii & DJ==jj,s);
end
end
Now RN has the random numbers and these are the same whenever a combination of id and ch is repeated. However, doing this at a larger scale (my data consists of 500,000 observations that combine 900 values for id with up to 25 values for ch), with even one random number (instead of 5), takes forever.
Is there any way to generate the matrix with random numbers that does not require all this manipulation? I have tried to use indices but I haven't figured out a clever way to do it.
Thanks,
Fernando

Best Answer

[uid, uida, uidc] = unique(id);
[uch, ucha, uchc] = unique(ch);
numid = length(uid);
numch = length(uch);
randmat = rand(numid, numch);
randobs = randmat( sub2ind([numid, numch], uidc, uchc) );
Note: the above will fail if the id and ch vectors are not the same length.