title: MATLAB loop optimization
body: <p>I have a matrix, <strong>matrix_logical(50000,100000)</strong>, that is a sparse logical matrix (a lot of falses, some true). I have to produce a matrix, <strong>intersect(50000,50000)</strong>, that, for each pair, <em>i,j</em>, of rows of <strong>matrix_logical(50000,100000)</strong>, stores the number of columns for which rows <em>i</em> and <em>j</em> have both "true" as the value.</p>
  
  <p>Here is the code I wrote:</p>
  
  <pre><code>% store in advance the nonzeros cols
  for i=1:50000
      nonzeros{i} = num2cell(find(matrix_logical(i,:)));
  end
  
  intersect = zeros(50000,50000);
  
  for i=1:49999
      a = cell2mat(nonzeros{i});
      for j=(i+1):50000
          b = cell2mat(nonzeros{j});
          intersect(i,j) = numel(intersect(a,b));
      end
  end
  </code></pre>
  
  <p>Is it possible to further increase the performance? It takes too long to compute the matrix. I would like to avoid the double loop in the second part of the code.</p>
  
  <p><strong>matrix_logical</strong> is sparse, but it is not saved as sparse in MATLAB because otherwise the performance become the worst possible.</p>