1
$\begingroup$

I was wondering whether there is a smart and efficient way in Matlab to compute the kronecker product of several 1D arrays.

What I mean is something like this

A = [a1, a2];
B = [b1, b2];
C = [c1, c2];
K = f(A,B,C) = [a1*b1*c1, a1*b1*c2, a1*b2*c1, ... ]

One possible way it is to use the kron(X,Y) function, but it has to be put inside a loop to obtain the aforementioned result since the kron function accepts only 2 arguments per time.

K = 1;
tot_arrays = [A, B, C];
for i=1:num_arrays
    K = kron(K,tot_arrays(:,i));
end

Isn't there a smarter and more efficient way to obtain the same result for the kron multiplication of more than 2 arrays per time?

Thanks

$\endgroup$
  • $\begingroup$ Have you already seen Fast Kronecker matrix multiplication in the exchange? $\endgroup$ – Mauro Vanzetto Sep 18 '17 at 15:59
  • $\begingroup$ Hi @MauroVanzetto, thanks for the reply. No, I never heard about it. However, after a quick check at the link you provided, it does not seem to be what I'm looking for. Thanks $\endgroup$ – FancyPants Sep 20 '17 at 21:55
3
$\begingroup$

Faster to write: I don't think there is. Faster to run with larger array lengths: the first thing I would try is the following.

>> a = [1 2];
>> b = [3 4];
>> c = [5 6];
>> a = reshape(a, [length(a) 1 1]);
>> b = reshape(b, [1 length(b) 1]);
>> c = reshape(c, [1 1 length(c)]);
>> P = a.*b.*c;
>> P = reshape(P, [1 length(P)])
P =
    15    30    20    40    18    36    24    48
$\endgroup$
  • $\begingroup$ Thanks for the reply. Which version of Matlab did you use to test this script? I tried it, but it does not seem to work. $\endgroup$ – FancyPants Sep 20 '17 at 21:54
  • $\begingroup$ @FancyPants It should work starting from R2016b. There have been some changes to how operators expand singleton dimensions there, which is necessary for a.*b.*c to work. If you have an older version, you have to use bsxfun instead to get the same behavior, but that works only with two arrays at the time. $\endgroup$ – Federico Poloni Sep 20 '17 at 22:00
  • $\begingroup$ @FancyPants If you type edit kron.m you'll see the definition similar to this. You can generalize it from there by removing the sparse stuff. $\endgroup$ – percusse Sep 21 '17 at 9:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.