Kronecker product: Difference between revisions

→‎{{header|Go}}: add library solutions
(Go solution)
(→‎{{header|Go}}: add library solutions)
Line 748:
 
=={{header|Go}}==
===Implementation===
<lang go>package main
 
Line 852 ⟶ 853:
|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>
===Library go.matrix===
<lang go>package main
 
import (
"fmt"
 
"github.com/skelterjohn/go.matrix"
)
 
func main() {
fmt.Println(matrix.Kronecker(
matrix.MakeDenseMatrixStacked([][]float64{
{1, 2},
{3, 4},
}),
matrix.MakeDenseMatrixStacked([][]float64{
{0, 5},
{6, 7},
})))
fmt.Println()
fmt.Println(matrix.Kronecker(
matrix.MakeDenseMatrixStacked([][]float64{
{0, 1, 0},
{1, 1, 1},
{0, 1, 0},
}),
matrix.MakeDenseMatrixStacked([][]float64{
{1, 1, 1, 1},
{1, 0, 0, 1},
{1, 1, 1, 1},
})))
}</lang>
{{out}}
<pre>
{ 0, 5, 0, 10,
6, 7, 12, 14,
0, 15, 0, 20,
18, 21, 24, 28}
 
{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,
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, 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>
===Library gonum/matrix===
Gonum/matrix doesn't have the Kronecker product, but here's an implementation using available methods.
<lang go>package main
 
import (
"fmt"
 
"github.com/gonum/matrix/mat64"
)
 
func kronecker(a, b mat64.Matrix) *mat64.Dense {
ar, ac := a.Dims()
br, bc := b.Dims()
k := mat64.NewDense(ar*br, ac*bc, nil)
for i := 0; i < ar; i++ {
for j := 0; j < ac; j++ {
s := k.Slice(i*br, (i+1)*br, j*bc, (j+1)*bc).(*mat64.Dense)
s.Scale(a.At(i, j), b)
}
}
return k
}
 
func main() {
fmt.Println(mat64.Formatted(kronecker(
mat64.NewDense(2, 2, []float64{
1, 2,
3, 4,
}),
mat64.NewDense(2, 2, []float64{
0, 5,
6, 7,
}))))
fmt.Println()
fmt.Println(mat64.Formatted(kronecker(
mat64.NewDense(3, 3, []float64{
0, 1, 0,
1, 1, 1,
0, 1, 0,
}),
mat64.NewDense(3, 4, []float64{
1, 1, 1, 1,
1, 0, 0, 1,
1, 1, 1, 1,
}))))
}</lang>
{{out}}
<pre>
⎡ 0 5 0 10⎤
⎢ 6 7 12 14⎥
⎢ 0 15 0 20⎥
⎣18 21 24 28⎦
 
⎡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⎥
⎢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 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>
 
1,707

edits