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):
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
Code1:
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
Code2:
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
Code3:
L_new = 0;
for n=1:N
suma = sum(fL(n,:));
L_new = L_new + maxfL(n) + log(suma);
end
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):
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)
Thanks for the answers!!
Stackoverflowwe don't do partial answers. Still to get on with it, what are the dimensions forz,maxfL?code2, would it befor d=1:Krather?