Matlab Matrix Generation with Random Elements

How can I generate a matrix with boolean elements, but the sum of each row is equal to some constant number.

+1
source share
2 answers

Suppose you want to have 20 columns ( n=20 ), and your vector a contains the number of desired in each row:

 n=20; a= [5 6 1 9 4]; X= zeros(numel(a),n); for k=1:numel(a) rand_order=randperm(n); row_entries=[ones(1,a(k)),zeros(1,na(k))]; row_entries=row_entries(rand_order); X(k,:)=row_entries; end X=boolean(X); 

What I am doing is generating me a random ordered array of rand_order indices, and then getting an array that contains the right number of units filled with zero. Change the order of these elements according to rand_order , saving it and converting it to logical. And due to using the for rand_order all the time, it computes again, so it gives you different locations for your output:

  1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 1 0 0 0 0 0 1 0 0 0 1 1 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 1 0 1 1 0 1 0 0 1 1 0 0 0 1 1 0 0 1 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 
+1
source

Is each line the same number?

 k = 5; m = 10; n = 10; [~, I] = sort(rand(m,n), 2) M = I <= k 

If you do not want to have the same number of 1 in each line, but rather have a vector pointing to the line, how many 1 do you want, you also need to use bsxfun :

 K = (1:10)'; %//' m = 10; n = 10; [~, I] = sort(rand(m,n), 2) M = bsxfun(@ge, K,I) 
+6
source

Source: https://habr.com/ru/post/1201389/


All Articles