sum of kronecker products
21 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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
2 Commenti
Risposta accettata
Matt J
il 6 Mag 2021
Modificato: Matt J
il 6 Mag 2021
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;
%%%% 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
Discrepancy = norm(result-result0,'fro') %check agreement
1 Commento
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Data Type Conversion in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!