title: Matlab efficiency - vectorization
body: <p>I have this Matlab code that runs, but i want to make it faster by removing the for loops and essentially do the same calculations using only matrices (my dataset is very large so i need this kind of optimizations):</p>
  
  <pre><code>Matrices dimensions: x(N,D), m(K,D), p(K), fL(N,K), maxf(N), maxfL(N), z(N,K).
  Also p, maxf, maxfL are row vectors
  </code></pre>
  
  <p>Code1:</p>
  
  <pre><code>f = zeros(N,K);
  maxf = zeros(1,N);
  
  for n=1:N
     for k=1:K
        % here i had a loop for d dimension but made it more efficient like this:
        f2 = x(n,:) * log(m(k,:))' + (1 - x(n,:)) * log(1 - m(k,:))';
        f(n,k) = log(p(k)) + f2;
     end
     maxf(n) = max(f(n,:));
     f(n,:) = f(n,:) - maxf(n);
  end
  </code></pre>
  
  <p>Code2:</p>
  
  <pre><code>for k=1:K
    sum2 = sum(z(:,k)); 
    p(k)= sum2/N;
    for d=1:D
       % here i had a n loop for sum1 and made it like this:
       sum1 = z(:,k)' * x(:,d); 
       m(k,d) = sum1/sum2;
    end
  end
  </code></pre>
  
  <p>Code3:</p>
  
  <pre><code>L_new = 0;
  for n=1:N
    suma = sum(fL(n,:));
    L_new = L_new + maxfL(n) + log(suma);
  end
  </code></pre>
  
  <p>I will now summarize some average execution times (results are in seconds) from using the below provided answers in my workload (N = 1000, K = 2, D = 784):</p>
  
  <pre><code>CodeNumber                      Execution Time
      1           3.98(for_loops), 1.01(Divakar), 0.5(Nishant)
      2           0.2(for_loops), 0.40-0.42(Divakar-2 approaches), 0.13(Nishant)
      3           0.03(for_loops), 0.0026(Divakar), 0.0024(Nishant)
  </code></pre>
  
  <p>Thanks for the answers!!</p>