title: Vectorize a for loop in which the input depends on the output
body: <p>I have a complicated problem about vectorization of a dependence for loop, I would like to have some helps from you.</p>
  
  <p>Let's <code>X1</code> be a vector with length <code>n1</code>, <code>X2</code> be a vector with length <code>n2</code>, <code>F1</code> be a <code>N1</code>x<code>n1</code> matrix, <code>F2</code> be a <code>N2</code>x<code>n2</code> matrix, <code>Q</code> be a <code>N1</code>x<code>N2</code> matrix, and the notation <code>p...</code> are index vectors. ntrapz is a function for trapezoidal numerical integration. I would like to compute the matrix <code>Q</code> as follows:</p>
  
  <pre><code>for i1=1:N1
      F1_13tmp=F1(i1, p1_13)';                       % ' 
      F1_13=F1_13tmp(:,ones(n2,1));
      for i2=1:N2
          F2_13 = F2(i2, p2_13);
          Q_13_13 = Q(p1_13, p2_13);
          Q(i1,i2) = Q(i1,i2) + 
                ntrapz(X2(p2_13), ntrapz(X1(p1_13)', Q_13_13.*F1_13).*F2_13);
      end
  end
  </code></pre>
  
  <p>The problem is that updating <code>Q(i1,i2)</code> changes the value of <code>Q_13_13 = Q(p1_13, p2_13)</code> for the next iteration. I would like to know if we can vectorize a such for loop. If not, any idea to speed up the code?</p>
  
  <p>Thank you in advance for your help.</p>