Create a randomized grouping matrix using one-liner

조회 수: 4 (최근 30일)
Rob G
Rob G 2020년 3월 7일
댓글: dpb 2020년 3월 8일
I'm trying to generate a randomized n x m, n>m, matrix that has a single 1 in a random column and 0s elsewhere for every row. It's easy with a for loop:
M = 10;
n = 150;
subj = zeros(n*M,M);
for subj_i = 1:n*M
subj(subj_i,randi(M)) = 1
end
But I'm trying to find a one-liner, here's my attempt:
subj = zeros(n*M,M);
subj(1:n*M,randi(M,1,n*M)) = 1
But it keeps generating all ones everywhere. It'd be great to not even need the initial zeros declaration and to have the option of each column having the same total.
UPDATE:
I figured out how to do it using the Statistics and Machine Learning toolbox, but it'd be good to figure out a way without it, and, again, some way to have equal group sizes would be nice:
dummyvar(randi(M,1,n*M))
  댓글 수: 3
Rob G
Rob G 2020년 3월 7일
I changed the title of the thread to read "randomized" grouping matrix. Does that help? Also, what if I said "random up to a degrees of freedom of n*M-1"?
dpb
dpb 2020년 3월 8일
Just pointing it out...if the constraint must be met then about the only way I know to do is to fill and then modify to match the constraint. Unless is evenly divisible in size, it may not be possible to be identically equal.
I guess w/o knowing any more, I'd use the solution given below and then if sum() isn't within tolerance of N+/- allowable number just pick the number to either add or subtract by column that are high/low. To keep the rule of only one/row have to do in pairs of one over, one under and swap columns' entries.

댓글을 달려면 로그인하십시오.

채택된 답변

dpb
dpb 2020년 3월 7일
Without the constraints, and without initialization,
>> R=[1:N].'; C=randi(M,N,1); % N,M num rows, columns respectively
>> accumarray([R C],ones(N,1))
ans =
0 1 0
0 0 1
1 0 0
0 0 1
0 1 0
>>
Runs the risk if N,M small can always not have every column in every realization of C (then again, it is a random permutation you say).
W/ initialization can ensure output will be full rank of NxM with
>> A=zeros(N,M);
>> A(sub2ind([N,M],R,C))=1
A =
0 1 0
0 0 1
1 0 0
0 0 1
0 1 0
>>

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by