sum of kronecker products

21 visualizzazioni (ultimi 30 giorni)
Mazdack Ameri
Mazdack Ameri il 6 Mag 2021
Modificato: Mazdack Ameri il 7 Mag 2021
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
Jan
Jan il 6 Mag 2021
What are the usual sizes for the inputs?
Mazdack Ameri
Mazdack Ameri il 7 Mag 2021
N > 30

Accedi per commentare.

Risposta accettata

Matt J
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;
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
  1 Commento
Mazdack Ameri
Mazdack Ameri il 7 Mag 2021
Modificato: Mazdack Ameri il 7 Mag 2021
It works Matt J, thank you so much!

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Data Type Conversion in Help Center e File Exchange

Prodotti


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by