title: How to create random graph of n vertices with c fixed neighbours in MATLAB?
body: <p>I have written a code in MATLAB that allows me to generate a random graph of <code>n</code> vertices, each with <code>c</code> fixed neighbours without loops (note the edges are directed, thus "a connected to b" does not imply "b connected to a").</p>
  
  <p>However, it is terribly inefficient, especially when I need to it work on magnitudes such as <code>n = 10000</code> and <code>c = 1000</code>. I was wondering if anyone could optimize it big time, or suggest anything constructive?</p>
  
  <pre><code>function [M]=matsrand(n,c)
  
  
  MM=0;   %arbitrary starting value
  while MM ~=n*c
  
      M = sparse(zeros(n));       
      ctin = zeros(1,n);  
  
  
      for i=1:n
          rp = randperm(n);   %generate vector of the randomly permuted order of n vertices
          rp(rp==i)=[];       %get rid of itself to avoid self connection
  
          noconnect=find(ctin(:)&gt;=c); %generate list that i is not allowed to connect to
          where=ismember(rp,noconnect);   %returns 1 to the subset noconnect in rp
          noconnectind=find(where);
  
          rp(noconnectind(:))=[];         %remove the neurons i is not allowed to connect to
  
          if length(rp)&lt;c
              break
          else
              r=rp(1:c);
          end
          M(i,r)=1;
          ctin(r)=ctin(r)+1;
  
      end
      MM=sum(ctin);
  end
  </code></pre>