title: vectorization of for-loops with if-conditions gets slower
body: <p>I have one for-loop that I'm working on vectorizing it. The problem is, once vectorized, the code is 3 times slower.
  The original code, which is part of a thermodynamic algorithm, is:</p>
  
  <pre><code>Matrix=rand(10,10,20);
  someMatrix=rand(50);
  m=5; n=6; CONSTj=9; CONSTk=10; maxGrid=5;
  Total=0;
  
  for var=0:maxGrid
      Factor=1;
      p=CONSTj-var;
      q=CONSTk-var;
  
      if p&gt;=1 &amp;&amp; q&gt;=1
          Factor=Matrix(n,m,p)*Matrix(m,n,q);
      elseif p&gt;=1 &amp;&amp; q&lt;1
          Factor=Matrix(n,m,p);
      elseif p&lt;1 &amp;&amp; q&gt;=1
          Factor=Matrix(m,n,q);
      end
  
      Total=Total+Factor*(someMatrix(m)^var);
  end
  </code></pre>
  
  <p>I vectorized it into:</p>
  
  <pre><code>Matrix=rand(10,10,20);
  someMatrix=rand(50);
  m=5; n=6; CONSTj=9; CONSTk=10; maxGrid=5;
  
  var=(0:maxGrid)';
  Factor=ones(maxGrid+1,1);
  tempoJ=zeros(maxGrid+1,1);
  tempoK=zeros(maxGrid+1,1);
  p=CONSTj-var;
  q=CONSTk-var;
  
  index1 = find(p&gt;=1 &amp; q&gt;=1);
  index2 = find(p&gt;=1 &amp; q&lt;1 );
  index3 = find(p&lt;1  &amp; q&gt;=1);
  
  tempoJ(index1)=squeeze(Matrix(n,m,p(index1)));
  tempoJ(index2)=squeeze(Matrix(n,m,p(index2)));
  tempoK(index1)=squeeze(Matrix(m,n,q(index1)));
  tempoK(index3)=squeeze(Matrix(m,n,q(index3)));
  
  Factor(index1)=tempoJ(index1).*tempoK(index1);
  Factor(index2)=tempoJ(index2);
  Factor(index3)=tempoK(index3);
  
  Total=Factor.*(someMatrix(m).^var);
  Total=sum(Total);
  </code></pre>
  
  <p>The profiler says that <em>find</em>, <em>squeeze</em> and <em>sum</em> are the functions that consume the most time. I believe that something can be done to get the information from the if-statement but I can't find a simpler way without altering the indices.</p>