title: Can I avoid double forcycle by bsxfun?
body: <p>I am wondering, if it is possible to use double bsxfun, or something similar. I have this piece of code:</p>
  
  <pre><code>N = 5;
  prob = [0.1 0.2 0 0.1; 0 0 0.05 0.1; 0.2 0.2 0 0.1];
  r = rand(size(prob,1),N);
  
  P = zeros(N, size(prob,1));
  csm = cumsum(normP([zeros(size(prob,1),1),prob]),2);
  
  for i = 1:N
   P(i,:) = sum(bsxfun(@ge,r(:,i),csm),2);
  end
  </code></pre>
  
  <p>Prob matrix contains rows with elements between 0 and 1, each row is probability distribution (after normalisation done by normP). First row of prob matrix is used to generate first element of vector P (values1,2 or 4), second row for the second element (values 3 or 4), and so on.</p>
  
  <pre><code>e.g.: P =
  
         2     4     2
         4     4     1
         2     4     2
         2     4     4
         2     3     1
  </code></pre>
  
  <p>I have already vectorised generating elements for one vector P, but I need to generate several (N) vectors. There must be way to avoid the for cycle.</p>
  
  <p>In the attachment, there is the normP function. I will be glad for help, thank you.</p>
  
  <p>Michal Roubalik</p>
  
  <p>P.S. Code of normP is here:</p>
  
  <pre><code>function nP = normP(P)
  %
  % Probability matrix normalization to hold sum of rows be equal to one
  % i.e. sum(nP,2) = ones(N,1)
  %
  % No dependencies
  srowP = sum(P,2);
  good  = srowP&gt;0;
  bad   = ~good;
  nP    = zeros(size(P));
  
  % good case
  if any(good)
      nP(good,:) = bsxfun(@rdivide, P(good,:), srowP(good));
  end
  % bad case
  if any(bad)
      nP(bad,:) = nan(size(P(bad,:)));
  end
  </code></pre>