Kronecker product: Difference between revisions

Content added Content deleted
(Frink)
Line 1,544: Line 1,544:


=={{header|Frink}}==
=={{header|Frink}}==
The Frink library [https://frinklang.org/fsp/colorize.fsp?f=Matrix.frink Matrix.frink] contains an implementation of Kronecker product. The following example demonstrates calculating the Kronecker product and typesetting the equations using Frink's layout routines.
The Frink library [https://frinklang.org/fsp/colorize.fsp?f=Matrix.frink Matrix.frink] contains an implementation of Kronecker product. However, the following example demonstrates calculating the Kronecker product and typesetting the equations using multidimensional arrays and no external libraries.
<lang frink>use Matrix.frink
<lang frink>a = [[1,2],[3,4]]
a = new Matrix[ [[1,2],[3,4] ]]
b = [[0,5],[6,7]]
b = new Matrix[ [[0,5],[6,7] ]]
println[formatProd[a,b]]
println[formatProd[a,b]]


c = new Matrix[ [[0,1,0],[1,1,1],[0,1,0] ]]
c = [[0,1,0],[1,1,1],[0,1,0]]
d = new Matrix[ [[1,1,1,1],[1,0,0,1],[1,1,1,1]] ]
d = [[1,1,1,1],[1,0,0,1],[1,1,1,1]]
println[formatProd[c,d]]
println[formatProd[c,d]]


formatProd[a,b] := formatTable[[[a.formatMatrix[], "\u2297", b.formatMatrix[], "=", a.KroneckerProduct[b].formatMatrix[]]]]</lang>
formatProd[a,b] := formatTable[[[formatMatrix[a], "\u2297", formatMatrix[b], "=", formatMatrix[KroneckerProduct[a,b]]]]]

KroneckerProduct[a, b] :=
{
[m,n] = a.dimensions[]
[p,q] = b.dimensions[]
rows = m p
cols = n q
n = new array[[rows, cols], 0]
for i=0 to rows-1
for j=0 to cols-1
n@i@j = a@(i div p)@(j div q) * b@(i mod p)@(j mod q)
return n
}</lang>
{{out}}
{{out}}
<pre>
<pre>
┌ ┐
│ 0 5 0 10│
│ 0 5 0 10│
│1 2│ │0 5│6 7 12 14│
┌ ┐
│3 4│ │6 7│ =0 15 0 20│
│1 2│ │0 5│ 6 7 12 14│
│18 21 24 28│
=
│3 4│ │6 7│ 0 15 0 20│
│0 0 0 0 1 1 1 1 0 0 0 0│
│18 21 24 28│
│0 0 0 0 1 0 0 1 0 0 0 0│
│0 0 0 0 1 1 1 1 0 0 0 0│
│0 1 0│ │1 1 1 1│ │1 1 1 1 1 1 1 1 1 1 1 1│
│0 0 0 0 1 1 1 1 0 0 0 0│
│ │
│1 1 1│ ⊗ │1 0 0 1│ = │1 0 0 1 1 0 0 1 1 0 0 1│
│0 1 0│ │1 1 1 1│ │1 1 1 1 1 1 1 1 1 1 1 1│
│0 0 0 0 1 0 0 1 0 0 0 0│
│0 0 0 0 1 1 1 1 0 0 0 0│
│0 0 0 0 1 0 0 1 0 0 0 0│
│0 0 0 0 1 1 1 1 0 0 0 0│
│0 0 0 0 1 1 1 1 0 0 0 0│
│0 1 0│ │1 1 1 1│ │1 1 1 1 1 1 1 1 1 1 1 1│
│ │ │ │ │ │
│1 1 1│ ⊗ │1 0 0 1│ = │1 0 0 1 1 0 0 1 1 0 0 1│
│ │ │ │ │ │
│0 1 0│ │1 1 1 1│ │1 1 1 1 1 1 1 1 1 1 1 1│
└ ┘ └ ┘ │ │
│0 0 0 0 1 1 1 1 0 0 0 0│
│ │
│0 0 0 0 1 0 0 1 0 0 0 0│
│ │
│0 0 0 0 1 1 1 1 0 0 0 0│
└ ┘
</pre>
</pre>