Create a randomized grouping matrix using one-liner
Afficher commentaires plus anciens
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 commentaires
dpb
le 7 Mar 2020
"and to have the option of each column having the same total."
Then it's no longer truly random but constrained.
Rob G
le 7 Mar 2020
dpb
le 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.
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!