Efficient way to multiply a matrix by each element of another matrix and store in one large matrix

I need to multiply a matrix A with each element of another matrix B. The result should be stored in one large matrix, C. This should work for arbitrarily large matrices.

To give a specific example:
Take to matrices AandB

A = [[A11 A12]  = [[1  2]
     [A21 A22]]    [3 4]]

B = [[B11 B12]  = [[11 12]
     [B21 B22]]    [13 14]]

The result should be:

C = [[A11*B11 A12*B11 A11*B12 A12*B12] = [[11 22 12 24]
     [A21*B11 A22*B11 A21*B12 A22*B12]    [33 44 36 48]
     [A11*B21 A12*B21 A11*B22 A12*B22]    [13 26 14 28]
     [A21*B21 A22*B21 A21*B22 A22*B22]]   [39 52 42 56]]

One solution would be to loop over all elements of B but this is probably inefficient and allocating the results of each iteration into matrix Cmight get tricky.

Any better ideas?

I’m sorry if this was asked before. If so, please just refer me to the right topic.

You might want to look at kron function.
As an example:

julia> A = rand(3:6, 2, 2)
2×2 Matrix{Int64}:
 3  5
 4  6

julia> M = rand(0:2, 3, 3)
3×3 Matrix{Int64}:
 0  0  1
 1  1  2
 2  0  1

julia> kron(M, A)
6×6 Matrix{Int64}:
 0   0  0  0  3   5
 0   0  0  0  4   6
 3   5  3  5  6  10
 4   6  4  6  8  12
 6  10  0  0  3   5
 8  12  0  0  4   6

(order of parameters imprtant! second parameter is the ‘small’ matrix tiling the result matrix)

4 Likes

What you want is exactly the Kronecker product B \otimes A, computed by the kron function as noted above.

These are arrays of arrays, which is not the same thing as a matrix (2d array) in Julia. (Unlike Python.) You want:

julia> A = [1 2
            3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> B = [11 12
            13 14]
2×2 Matrix{Int64}:
 11  12
 13  14

julia> using LinearAlgebra # for kron

julia> C = kron(B, A)
4×4 Matrix{Int64}:
 11  22  12  24
 33  44  36  48
 13  26  14  28
 39  52  42  56
1 Like

Awesome. I knew I should have paid more attention in my linear algebra course.

Thanks a lot!