title: Select n weighted elements by index from a very large array in MATLAB
body: <p>Suppose I have a very large square matrix, M(i, j), such that each element in the matrix represents the probability that the element will be chosen in a weighted random selection. I need to sample n elements from the matrix (by the (i, j) indices) with replacement. The weights will change on every iteration of the main loop.</p>
  
  <p>Currently, I am using something like the following:
  </p>
  
  <pre><code>for m = 1:M_size
      xMean(m) = mean(M(:, m));
  end
  
  [~, j_list] = histc(rand(n, 1), cumsum([0; xMean'./sum(xMean)']));
  for c = 1:n
      [~, i_list(c)] = ...
        histc(rand(1, 1), cumsum([0;, M(:, j_list(c))./sum(M(:, j_list(c)))]));
  end
  </code></pre>
  
  <p>But this seems to be a rather clunky method, that also takes a very long time due to the for loop. Is there a more efficient method? Perhaps if I vectorize the matrix in some way?</p>
  
  <p>*Edit I should mention that I do not have access to a statistics toolbox</p>
  
  <p>Many thanks in advance.</p>