title: How to Vectorize a Nested Loop
body: <p>I'm having trouble visualizing how to vectorize this set of loops. Any guidance would be appreciated.</p>
  
  <pre><code>ind_1 = [1,2,3];
  ind_2 = [1,2,4];
  K = zeros(3,3,3,3,3,3,3,3,3);
  pp = rand(4,4,4);
  
  for s = 1:3
   for t = 1:3
    for k = 1:3
     for l = 1:3
      for m = 1:3
       for n = 1:3
        for o = 1:3
         for p = 1:3
          for r = 1:3
           % the following loops are singular valued except when
           % y=3 for ind_x(y) in this case
           for a_s = ind_1(s):ind_2(s)
            for a_t = ind_1(t):ind_2(t)
             for a_k = ind_1(k):ind_2(k)
              for a_l = ind_1(l):ind_2(l)
               for a_m = ind_1(m):ind_2(m)
                for a_n = ind_1(n):ind_2(n)
                 for a_o = ind_1(o):ind_2(o)
                  for a_p = ind_1(p):ind_2(p)
                   for a_r = ind_1(r):ind_2(r)
                    K(s,t,k,l,m,n,o,p,r) = K(s,t,k,l,m,n,o,p,r) + ...
                      pp(a_s, a_t, a_r) * pp(a_k, a_l, a_r) * ...
                      pp(a_n, a_m, a_s) * pp(a_o, a_n, a_t) * ...
                      pp(a_p, a_o, a_k) * pp(a_m, a_p, a_l);
                   end
                  end
                 end
                end
               end
              end
             end
            end
           end
          end
         end
        end
       end
      end
     end
    end
   end
  end
  </code></pre>
  
  <p>EDIT:</p>
  
  <p>The code is creating a rank-9 tensor with indices from 1 to 3 by summing the values of a product of <code>pp</code>s one or two times for each index, depending on the value of <code>ind_1</code> and <code>ind_2</code>.</p>
  
  <p>EDIT:</p>
  
  <p>Here is a 3d example, though bear in mind that the fact that the indices of <code>pp</code> are simply permuted is not preserved in the 9d version:</p>
  
  <pre><code>ind_1 = [1,2,3];
  ind_2 = [1,2,4];
  K = zeros(3,3,3);
  pp = rand(4,4,4);
  
  for s = 1:3
   for t = 1:3
    for k = 1:3
     % the following loops are singular valued except when
     % y=3 for ind_x(y) in this case
     for a_s = ind_1(s):ind_2(s)
      for a_t = ind_1(t):ind_2(t)
       for a_k = ind_1(k):ind_2(k)
        K(s,t,k) = K(s,t,k) + ...
          pp(a_s, a_t, a_r) * pp(a_t, a_s, a_k) * ...
          pp(a_k, a_t, a_s) * pp(a_k, a_s, a_t);
       end
      end
     end
    end
   end
  end
  </code></pre>