MATLAB: Sum of kronecker products

arrayMATLABmatlab function

Hi! I am trying to write in a more efficient way the following code, possibly without the for cycles.
Thank you in advance. var1, var2 are N x N x N arrays. var3 is a N X N array.
function sum = kronecker_sum(var1,var2,var3)
N = size(var1,1);
sum = zeros(N^2,N^2);
for i = 1:N
for j = 1:N
sum = sum + kron(var1(:,:,i),var2(:,:,j))*var3(i,j);
end
end
end

Best Answer

This solution is not completely free of loops (because of num2cell and cell2mat), but you can see below that it is still much faster:
N=35;
[var1,var2]=deal(rand(N,N,N));
var3=rand(N);
%%%% Original Method
tic;
accum = zeros(N^2,N^2);
for i = 1:N
for j = 1:N
accum = accum + kron(var1(:,:,i),var2(:,:,j))*var3(i,j);
end
end
result0=accum;
toc;
Elapsed time is 2.844959 seconds.
%%%% Proposed Alternative
tic;
Var1=reshape(var1,N^2,N);
Var2=reshape(var2,N^2,N);
tmp = num2cell( reshape( Var2*var3.'*Var1.', N,N,[]), [1,2]);
result=cell2mat( reshape(tmp,N,N) );
toc
Elapsed time is 0.058188 seconds.
Discrepancy = norm(result-result0,'fro') %check agreement
Discrepancy = 1.8576e-10