common random number when satisfying certain conditions
1 次查看(过去 30 天)
显示 更早的评论
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
2 个评论
Walter Roberson
2013-3-20
50000 observations -- do you mean you want 50000 random numbers generated? 900 * 25 < 50000, so is the task to verify that the observations meet the condition if id&ch being consistent ?
采纳的回答
Walter Roberson
2013-3-20
编辑:Walter Roberson
2013-3-20
[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.
2 个评论
Walter Roberson
2013-3-20
Sorry, I missed accessing randmat() at those locations; I have edited that into place.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!