When I started working with matlab sometime ago in the university, my supervisor would kill me if he saw any unnecessary for loop (he would ask for exchanging it for k
clear all;
ntimes = 1000;
r = 100;
c = 100;
d = 100;
A = rand(r, c, d);
B = rand(r, c, d);
tic
for i = 1:ntimes
for j = 1 : d
result = A(:, :, j) * B(:, :, j);
end
end
toc
A_cell = num2cell(A, [1 2]);
B_cell = num2cell(B, [1 2]);
tic
for i = 1 : ntimes
result2 = cellfun(@(x, y) x*y, A_cell, B_cell, 'uni', 0);
end
toc
Try this maybe. Test it for few more times. On average, cellfun is faster than the double loop.