title: filling a matrix with random integers from a range according to a rule
body: <p>I'm using the matrix as an initial population for multiobjective optimization using NSGA-II in matlab. The size of my chromosome vector,(C), is <code>1x192</code> and each gene must be within the range <code>0&lt;=gene&lt;=40</code> and the genes must be integers. The rule is that the sum of groupings of 6 genes must be less or equal to 40.that is:</p>
  <pre><code>sum(reshape(6,[]))&lt;=40
  </code></pre>
  <p>I've use the following code but it outputs either an all-zero population matrix(population matrix=vertical concatenation of 500 chromosomes) or a matrix that does not satisfy the rule:</p>
  <pre><code>     X=zeros(500,192);
       while i&lt;501
         r=randi(40,6,32);
          if nnz(((sum(r))./40)&gt;1)==0
           X(i,:)=reshape(r,1,[]);
           i=i+1;
           clear r;
          else
           clear r;
          end
       end
  </code></pre>
  <p>It is also taking forever to exit the while loop.
  What am I doing wrong here? Is there another way of doing the above?</p>
  <p>I've also tried this:</p>
  <pre><code>i=1;
  while i&lt;17500
   r=randi([1,40],6,1);
   s=sum(r);
    if s&lt;=40
     X(:,i)=r;
     i=i+1;
    else
     clear r;
    end
  end
  X=unique(X','rows')';
  A=X(:,randperm(size(X,2)));
  A=X(randperm(size(X,1)),:);
  </code></pre>
  <p>The above tries to create random columns that will be reshaped to the population matrix. But the numbers are repeating; i.e in the 17500(16448 after removing duplicate columns) columns there is no occurrence of the numbers 37 and 40. Is there any way I can optimize the spread of the generated random numbers?</p>
  <p>@0x90
  I have a vector,called 'chromosome', of size <code>1x192</code> and each successive group of 6 members(called phenotype) must sum to 40 or less. To make it clearer:
  <img src="https://i.stack.imgur.com/3jaUH.png" alt="problem details" />
  That is, each P must be an integer in the range 0 to 40 inclusive and the sum at each phenotype must be &lt;=40. I need 500 chromosomes like this.</p>
  <p>I hope it makes sense now. &gt;&lt;</p>