0

I'm looking to express in pure python what is being done by the np.kron function.

Let's say i have these lists:

v1 =  [1, 0, 0, 1]
v2 = [1, 0, 0, 1]

i would like to define a function that would create a list of lists by multiplying v1 by each element in v2. So these two lists would produce 4 lists:

[[1 * v1[0]],[0 * v1[1]],[ * v1[3]],[1 * v1[3]]]

Currently, i've been messing around with a bunch of stuff. but cant get it to work. for example, when i run this code i get a 4x2 matrix:

i = [[a*b for a in eye] for b in eye2]

>>[[1, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 1]]

when i convert to np.array and reformat it, it doesn't quite look right:

print(np.array(i).reshape(4,4))

[[1 0 0 1]
 [0 0 0 0]
 [0 0 0 0]
 [1 0 0 1]]

if np.kron is passed (v1, v2), it would give:

[[1 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]]

which is a beautiful 4 x 4 identity matrix; thats what im looking for.

neutrino
  • 894
  • 8
  • 23
  • the kron function uses the kronecker product [here](https://stackoverflow.com/questions/16330971/efficiently-computing-element-wise-product-of-transition-matrices-mm-nn) for the code to implement the kronecker product. – recurseuntilfor Aug 02 '20 at 01:39

1 Answers1

1

You need to check that the calculation are done in the right order as in this image. Keep in mind this is the kronecker product not the tensor product as this is what you have stated in the problem description not the title.

enter image description here

import numpy as np

v1 = [1, 0, 0, 1]
v2 = [1, 0, 0, 1]

v1 = np.array(v1).reshape(2, 2)
v2 = np.array(v2).reshape(2, 2)

i = [[num1 * num2 for num1 in elem1 for num2 in v2[row]] for elem1 in v1 for row in range(len(v2))]

print(' ')

print("With list comprehension: ")
print(np.array(i).reshape(4, 4))

print(' ')

print("With numpy kron: ")
print(np.kron(v1, v2))
recurseuntilfor
  • 2,293
  • 1
  • 12
  • 17