Create a randomized grouping matrix using one-liner
2 views (last 30 days)
Show older comments
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 Comments
dpb
on 8 Mar 2020
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.
Accepted Answer
dpb
on 7 Mar 2020
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
>>
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!