sum of kronecker products

조회 수: 17 (최근 30일)
Mazdack Ameri
Mazdack Ameri 2021년 5월 6일
편집: Mazdack Ameri 2021년 5월 7일
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
Jan
Jan 2021년 5월 6일
What are the usual sizes for the inputs?
Mazdack Ameri
Mazdack Ameri 2021년 5월 7일
N > 30

댓글을 달려면 로그인하십시오.

채택된 답변

Matt J
Matt J 2021년 5월 6일
편집: Matt J 2021년 5월 6일
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
Mazdack Ameri
Mazdack Ameri 2021년 5월 7일
편집: Mazdack Ameri 2021년 5월 7일
It works Matt J, thank you so much!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by