Matlab Generating a Matrix with random elements

后端 未结 2 1570
忘掉有多难
忘掉有多难 2021-01-14 22:15

How can I generate a Matrix with Boolean elements, but the sum of each row is equal to a certain constant number.

2条回答
  •  無奈伤痛
    2021-01-14 22:36

    Lets say you want to have 20 columns (n=20) and your vector a contains the number of ones you want 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,n-a(k))];
        row_entries=row_entries(rand_order);
        X(k,:)=row_entries;
    end
    X=boolean(X);
    

    What I do is generate me a random ordered index array rand_order then getting an array which contains the wanted number of ones filled with zero. Reorder those elements according to rand_order saving it and converting it to logical. And because of the use of a for loop rand_order is all the time computed again, so giving 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
    

提交回复
热议问题