Kronecker product: Difference between revisions

Added Yabasic
m (→‎{{header|Phix}}: added syntax colouring the hard way)
(Added Yabasic)
 
(29 intermediate revisions by 19 users not shown)
Line 49:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V a1 = [[1, 2], [3, 4]]
V b1 = [[0, 5], [6, 7]]
 
Line 82:
V result2 = kronecker(a2, b2)
L(elem) result2
print(elem)</langsyntaxhighlight>
 
{{out}}
Line 103:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Kronecker product 06/04/2017
KRONECK CSECT
USING KRONECK,R13 base register
Line 244:
R DS (NR*NR)F r(nr,nr)
YREGS
END KRONECK</langsyntaxhighlight>
{{out}}
<pre>
Line 261:
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>
 
=={{header|Action!}}==
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre>
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">CARD EndProg ;required for ALLOCATE.ACT
 
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
 
DEFINE PTR="CARD"
DEFINE MATRIX_SIZE="4"
TYPE Matrix=[
BYTE width,height
PTR data]
 
PTR FUNC CreateEmpty(BYTE w,h)
Matrix POINTER m
 
m=Alloc(MATRIX_SIZE)
m.width=w
m.height=h
m.data=Alloc(2*w*h)
RETURN (m)
 
PTR FUNC Create(BYTE w,h INT ARRAY a)
Matrix POINTER m
 
m=CreateEmpty(w,h)
MoveBlock(m.data,a,2*w*h)
RETURN (m)
 
PROC Destroy(Matrix POINTER m)
Free(m.data,2*m.width*m.height)
Free(m,MATRIX_SIZE)
RETURN
 
PTR FUNC Product(Matrix POINTER m1,m2)
Matrix POINTER m
BYTE x1,x2,y1,y2,i1,i2,i
INT ARRAY a1,a2,a
 
m=CreateEmpty(m1.width*m2.width,m1.height*m2.height)
a1=m1.data
a2=m2.data
a=m.data
i=0
FOR y1=0 TO m1.height-1
DO
FOR y2=0 TO m2.height-1
DO
FOR x1=0 TO m1.width-1
DO
FOR x2=0 TO m2.width-1
DO
i1=y1*m1.width+x1
i2=y2*m2.width+x2
a(i)=a1(i1)*a2(i2)
i==+1
OD
OD
OD
OD
RETURN (m)
 
PROC PrintMatrix(Matrix POINTER m BYTE x,y,colw)
BYTE i,j
CHAR ARRAY tmp(10)
INT ARRAY d
 
d=m.data
FOR j=0 TO m.height-1
DO
Position(x,y+j)
IF j=0 THEN
Put($11)
ELSEIF j=m.height-1 THEN
Put($1A)
ELSE
Put($7C)
FI
 
FOR i=0 TO m.width-1
DO
StrI(d(j*m.width+i),tmp)
Position(x+1+(i+1)*colw+i-tmp(0),y+j)
Print(tmp)
OD
Position(x+1+m.width*colw+(m.width-1),y+j)
IF j=0 THEN
Put($05)
ELSEIF j=m.height-1 THEN
Put($03)
ELSE
Put($7C)
FI
OD
RETURN
 
PROC Test1()
Matrix POINTER m1,m2,m3
INT ARRAY a1=[1 2 3 4],a2=[0 5 6 7]
m1=Create(2,2,a1)
m2=Create(2,2,a2)
m3=Product(m1,m2)
 
PrintMatrix(m1,0,2,1)
Position(5,3) Put('x)
PrintMatrix(m2,6,2,1)
Position(11,3) Put('=)
PrintMatrix(m3,12,1,2)
 
Destroy(m1)
Destroy(m2)
Destroy(m3)
RETURN
 
PROC Test2()
Matrix POINTER m1,m2,m3
INT ARRAY a1=[0 1 0 1 1 1 0 1 0],
a2=[1 1 1 1 1 0 0 1 1 1 1 1]
 
m1=Create(3,3,a1)
m2=Create(4,3,a2)
m3=Product(m1,m2)
 
PrintMatrix(m1,0,7,1)
Position(7,8) Put('x)
PrintMatrix(m2,8,7,1)
Position(17,8) Put('=)
PrintMatrix(m3,2,11,1)
 
Destroy(m1)
Destroy(m2)
Destroy(m3)
RETURN
 
PROC Main()
 
AllocInit(0)
Put(125) ;clear the screen
Test1()
Test2()
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Kronecker_product.png Screenshot from Atari 8-bit computer]
<pre>
┌ 0 5 0 10┐
┌1 2┐ ┌0 5┐ │ 6 7 12 14│
└3 4┘x└6 7┘=│ 0 15 0 20│
└18 21 24 28┘
 
 
┌0 1 0┐ ┌1 1 1 1┐
│1 1 1│x│1 0 0 1│=
└0 1 0┘ └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│
│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>
 
Line 267 ⟶ 434:
{{works with|Ada|Ada|83}}
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Ada.Integer_Text_IO;
 
Line 321 ⟶ 488:
Ada.Text_IO.New_Line;
end loop;
end Kronecker_Product;</langsyntaxhighlight>
{{out}}
<pre> 0 5 0 10
Line 340 ⟶ 507:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN
# multiplies in-place the elements of the matrix a by the scaler b #
OP *:= = ( REF[,]INT a, INT b )REF[,]INT:
Line 402 ⟶ 569:
)
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 423 ⟶ 590:
=={{header|APL}}==
{{works with|Dyalog APL}}
<langsyntaxhighlight lang="apl">kprod ← ⊃ (,/ (⍪⌿ (⊂[3 4] ∘.×)))</langsyntaxhighlight>
 
{{out}}
Line 451 ⟶ 618:
└─────┴───────┴───────────────────────┘</pre>
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">------------ KRONECKER PRODUCT OF TWO MATRICES -------------
 
-- kprod :: [[Num]] -> [[Num]] -> [[Num]]
Line 638 ⟶ 805:
on unlines(xs)
intercalate(linefeed, xs)
end unlines</langsyntaxhighlight>
{{Out}}
<pre>{0, 5, 0, 10}
Line 654 ⟶ 821:
{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>
 
=={{header|Arturo}}==
{{trans|Kotlin}}
<syntaxhighlight lang="rebol">define :matrix [X][
print: [
result: ""
loop this\X 'arr [
result: result ++ "[" ++
(join.with:" " map to [:string] arr 'item -> pad item 3) ++
"]\n"
]
return result
]
]
 
kroneckerProduct: function [a,b][
M: size a\X, N: size first a\X
P: size b\X, Q: size first b\X
result: to :matrix @[new array.of:M*P array.of:N*Q 0]
 
loop 0..dec M 'i [
loop 0..dec N 'j [
loop 0..dec P 'k [
loop 0..dec Q 'l [
result\X\[k + i * P]\[l + j * Q]: a\X\[i]\[j] * b\X\[k]\[l]
]
]
]
]
return result
]
A1: to :matrix [[[1 2] [3 4]]]
B1: to :matrix [[[0 5] [6 7]]]
 
print "Matrix A:"
print A1
 
print "Matrix B:"
print B1
 
print "Kronecker Product:"
print kroneckerProduct A1 B1
 
A2: to :matrix [[[0 1 0] [1 1 1] [0 1 0]]]
B2: to :matrix [[[1 1 1 1] [1 0 0 1] [1 1 1 1]]]
 
print "Matrix A:"
print A2
 
print "Matrix B:"
print B2
 
print "Kronecker Product:"
print kroneckerProduct A2 B2</syntaxhighlight>
 
{{out}}
 
<pre>Matrix A:
[ 1 2]
[ 3 4]
 
Matrix B:
[ 0 5]
[ 6 7]
 
Kronecker Product:
[ 0 5 0 10]
[ 6 7 12 14]
[ 0 15 0 20]
[ 18 21 24 28]
 
Matrix A:
[ 0 1 0]
[ 1 1 1]
[ 0 1 0]
 
Matrix B:
[ 1 1 1 1]
[ 1 0 0 1]
[ 1 1 1 1]
 
Kronecker Product:
[ 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>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">KroneckerProduct(a, b){
prod := [], r:= 1, c := 1
for i, aa in a
for j, bb in b
{
for k, x in aa
for l, y in bb
prod[R , C++] := x * y
r++, c:= 1
}
return prod
}</syntaxhighlight>
Examples:<syntaxhighlight lang="autohotkey">a := [[1, 2], [3, 4]]
b := [[0, 5], [6, 7]]
P := KroneckerProduct(a, b)
 
a :=[[0,1,0], [1,1,1], [0,1,0]]
b := [[1,1,1,1], [1,0,0,1], [1,1,1,1]]
Q := KroneckerProduct(a, b)
 
; show results
for row, obj in P
{
for col, v in obj
result .= v "`t"
result .= "`n"
}
result .= "`n"
for row, obj in Q
{
for col, v in obj
result .= v "`t"
result .= "`n"
}
MsgBox % result
return
</syntaxhighlight>
{{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>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f KRONECKER_PRODUCT.AWK
BEGIN {
Line 722 ⟶ 1,035:
return(n)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 762 ⟶ 1,075:
[ 0 0 0 0 1 1 1 1 0 0 0 0 ]
</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">arraybase 1
dim a(2, 2)
a[1,1] = 1 : a[1,2] = 2 : a[2,1] = 3 : a[2,2] = 4
dim b(2, 2)
b[1,1] = 0 : b[1,2] = 5 : b[2,1] = 6 : b[2,2] = 7
call kronecker_product(a, b)
 
print
dim x(3, 3)
x[1,1] = 0 : x[1,2] = 1 : x[1,3] = 0
x[2,1] = 1 : x[2,2] = 1 : x[2,3] = 1
x[3,1] = 0 : x[3,2] = 1 : x[3,3] = 0
dim y(3, 4)
y[1,1] = 1 : y[1,2] = 1 : y[1,3] = 1 : y[1,4] = 1
y[2,1] = 1 : y[2,2] = 0 : y[2,3] = 0 : y[2,4] = 1
y[3,1] = 1 : y[3,2] = 1 : y[3,3] = 1 : y[3,4] = 1
call kronecker_product(x, y)
end
 
subroutine kronecker_product(a, b)
ua1 = a[?][]
ua2 = a[][?]
 
ub1 = b[?][]
ub2 = b[][?]
 
for i = 1 to ua1
for k = 1 to ub1
print "[";
for j = 1 to ua2
for l = 1 to ub2
print rjust(a[i, j] * b[k, l], 2);
if j = ua1 and l = ub2 then
print "]"
else
print " ";
endif
next
next
next
next
end subroutine</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">print
dim a(2, 2)
a(1,1) = 1 : a(1,2) = 2 : a(2,1) = 3 : a(2,2) = 4
dim b(2, 2)
b(1,1) = 0 : b(1,2) = 5 : b(2,1) = 6 : b(2,2) = 7
kronecker_product(a, b)
 
print
dim a(3, 3)
a(1,1) = 0 : a(1,2) = 1 : a(1,3) = 0
a(2,1) = 1 : a(2,2) = 1 : a(2,3) = 1
a(3,1) = 0 : a(3,2) = 1 : a(3,3) = 0
dim b(3, 4)
b(1,1) = 1 : b(1,2) = 1 : b(1,3) = 1 : b(1,4) = 1
b(2,1) = 1 : b(2,2) = 0 : b(2,3) = 0 : b(2,4) = 1
b(3,1) = 1 : b(3,2) = 1 : b(3,3) = 1 : b(3,4) = 1
kronecker_product(a, b)
end
 
sub kronecker_product(a, b)
local i, j, k, l
ua1 = arraysize(a(), 1)
ua2 = arraysize(a(), 2)
ub1 = arraysize(b(), 1)
ub2 = arraysize(b(), 2)
 
for i = 1 to ua1
for k = 1 to ub1
print "[";
for j = 1 to ua2
for l = 1 to ub2
print a(i, j) * b(k, l) using "##";
if j = ua1 and l = ub2 then
print "]"
else
print " ";
endif
next
next
next
next
end sub</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">KProd ← ∾·<⎉2 ×⌜</syntaxhighlight>
 
or
 
<syntaxhighlight lang="bqn">KProd ← ∾ ×⟜<</syntaxhighlight>
 
Example:
 
<syntaxhighlight lang="bqn">l ← >⟨1‿2, 3‿4⟩
r ← >⟨0‿5, 6‿7⟩
 
l KProd r</syntaxhighlight>
 
<pre>
┌─
╵ 0 5 0 10
6 7 12 14
0 15 0 20
18 21 24 28
</pre>
 
([https://mlochbaum.github.io/BQN/try.html#code=S1Byb2Qg4oaQIOKIvsK3POKOiTLDl+KMnAoKbCDihpAgPuKfqDHigL8yLCAz4oC/NOKfqQpyIOKGkCA+4p+oMOKAvzUsIDbigL834p+pCgpsIEtQcm9kIHIK online REPL])
 
=={{header|C}}==
Entering and printing matrices on the console is tedious even for matrices with 4 or more rows and columns. This implementation reads and writes the matrices from and to files. Matrices are taken as double type in order to cover as many use cases as possible.
 
<syntaxhighlight lang="c">
<lang C>
#include<stdlib.h>
#include<stdio.h>
Line 842 ⟶ 1,275:
printf("\n\n\nKronecker product of the two matrices written to %s.",output);
}
</syntaxhighlight>
</lang>
 
Input file :
Line 881 ⟶ 1,314:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections;
using System.Collections.Generic;
Line 934 ⟶ 1,367:
}
 
}</langsyntaxhighlight>
{{out}}
<pre>
Line 953 ⟶ 1,386:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <cassert>
#include <iomanip>
#include <iostream>
Line 1,051 ⟶ 1,484:
test2();
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 1,078 ⟶ 1,511:
=={{header|D}}==
{{Trans|Go}}
<syntaxhighlight lang="d">
<lang D>
import std.stdio, std.outbuffer;
 
Line 1,132 ⟶ 1,565:
sample(C,D);
}
</syntaxhighlight>
</lang>
 
Output:
Line 1,170 ⟶ 1,603:
| 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>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// Kronecker product. Nigel Galloway: August 31st., 2023
open MathNet.Numerics
open MathNet.Numerics.LinearAlgebra
let m1,m2,m3,m4=matrix [[1.0;2.0];[3.0;4.0]],matrix [[0.0;5.0];[6.0;7.0]],matrix [[0.0;1.0;0.0];[1.0;1.0;1.0];[0.0;1.0;0.0]],matrix [[1.0;1.0;1.0;1.0];[1.0;0.0;0.0;1.0];[1.0;1.0;1.0;1.0]]
printfn $"{(m1.KroneckerProduct m2).ToMatrixString()}"
printfn $"{(m3.KroneckerProduct m4).ToMatrixString()}"
</syntaxhighlight>
{{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>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2020-01-23}}
<langsyntaxhighlight lang="factor">USING: kernel math.matrices.extras prettyprint ;
 
{ { 1 2 } { 3 4 } }
Line 1,180 ⟶ 1,640:
{ { 0 1 0 } { 1 1 1 } { 0 1 0 } }
{ { 1 1 1 1 } { 1 0 0 1 } { 1 1 1 1 } }
[ kronecker-product . ] 2bi@</langsyntaxhighlight>
{{out}}
<pre>
Line 1,200 ⟶ 1,660:
The plan is to pass the two arrays to a subroutine, which will return their Kronecker product as a third parameter. This relies on the expanded array-handling facilities introduced with F90, especially the ability of a subroutine to allocate an array of a size of its choosing, this array being a parameter to the subroutine. Some compilers offering the "allocate" statement do not handle this! Further features of the MODULE protocol of F90 allow arrays passed to a subroutine to have their sizes ascertained in the subroutine (via function UBOUND, ''etc.'') rather than this information being supplied via the programmer coding additional parameters. This is not all to the good: multi-dimensional arrays must therefore be the actual size of their usage rather than say A(100,100) but only using the first fifty elements (in one place) and the first thirty in another. Thus, for such usage the array must be re-allocated the correct size each time, and, the speed of access to such arrays is reduced - see [[Sequence_of_primorial_primes#Fixed-size_data_aggregates]] for an example. Similarly, suppose a portion of a large array is to be passed as a parameter, as is enabled by F90 syntax such as <code>A(3:7,9:12)</code> to select a 5x4 block: those elements will ''not'' be in contiguous memory locations, as is expected by the subroutine, so they will be copied into a temporary storage area that will become the parameter and their values will be copied back on return. Copy-in copy-out, instead of by reference. With large arrays, this imposes a large overhead. A further detail of the MODULE protocol when passing arrays is that if the parameter's declaration does not specify the lower bound, it will be treated as if it were one even if the actual array is declared otherwise - see [[Array_length#Fortran]] for example.
 
In older-style Fortran, the arrays would be of some "surely-big-enough" size, fixed at compile time, and there would be additional parameters describing the bounds in use for each invocation. Since no array-assignment statements were available, there would be additional DO-loops to copy each block of values. In all versions of Fortran, the ordering of array elements in storage is "column-major" so that the DATA statement appears to initialise the arrays with their transpose - see [[Matrix_transposition#Fortran]] for example. As a result, the default output order for an array, if written as just <code>WRITE (6,*) A</code> will be that of the transposed order, just as with the default order of the DATA statement's data. To show the desired order of A(''row'',''column''), the array must be written with explicit specification of the order of elements, as is done by subroutine SHOW: columns across the page, rows running down the page. <langsyntaxhighlight Fortranlang="fortran"> MODULE ARRAYMUSH !A rather small collection.
CONTAINS !For the specific problem only.
SUBROUTINE KPRODUCT(A,B,AB) !AB = Kronecker product of A and B, both two-dimensional arrays.
Line 1,256 ⟶ 1,716:
CALL SHOW (6,AB)
 
END</langsyntaxhighlight>
 
Output:
Line 1,280 ⟶ 1,740:
</pre>
 
An alternative approach is not to produce the array AB at all, just calculate its elements as needed. Using the array dimension variables as defined above, <langsyntaxhighlight Fortranlang="fortran">AB(i,j) = A((i - 1)/RB + 1,(j - 1)/CB + 1)*B(MOD(i - 1,RB) + 1,MOD(j - 1,CB) + 1))</langsyntaxhighlight> with the subtracting and adding of one necessary because array indexing starts with row one and column one. With F90, they could start at zero (or any desired value) but if so, you will have to be very careful with counting. For instance, <code>DO I = 1,RA</code> must become <code>DO I = 0,RA - 1</code> and so forth.
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 06-04-2017
' compile with: fbc -s console
 
Line 1,333 ⟶ 1,793:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>[ 0 5 0 10]
Line 1,349 ⟶ 1,809:
[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>
 
=={{header|Frink}}==
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.
<syntaxhighlight lang="frink">a = [[1,2],[3,4]]
b = [[0,5],[6,7]]
println[formatProd[a,b]]
 
c = [[0,1,0],[1,1,1],[0,1,0]]
d = [[1,1,1,1],[1,0,0,1],[1,1,1,1]]
println[formatProd[c,d]]
 
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
}</syntaxhighlight>
{{out}}
<pre>
┌ ┐
│ 0 5 0 10│
┌ ┐ ┌ ┐ │ │
│1 2│ │0 5│ │ 6 7 12 14│
│ │ ⊗ │ │ = │ │
│3 4│ │6 7│ │ 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│
┌ ┐ ┌ ┐ │ │
│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>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Kronecker_product}}
 
'''Solution'''
 
Kronecker product is an intrinsec operation in Fōrmulæ
 
'''Test case 1'''
 
[[File:Fōrmulæ - Kronecker product 01.png]]
 
[[File:Fōrmulæ - Kronecker product 02.png]]
 
'''Test case 2'''
 
[[File:Fōrmulæ - Kronecker product 03.png]]
 
[[File:Fōrmulæ - Kronecker product 04.png]]
 
A function to calculate the Kronecker product can also be written:
 
[[File:Fōrmulæ - Kronecker product 05.png]]
 
[[File:Fōrmulæ - Kronecker product 06.png]]
 
[[File:Fōrmulæ - Kronecker product 02.png]]
 
=={{header|Go}}==
===Implementation===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,424 ⟶ 1,969:
{1, 1, 1, 1},
})
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,459 ⟶ 2,004:
 
===Library go.matrix===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,489 ⟶ 2,034:
{1, 1, 1, 1},
})))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,509 ⟶ 2,054:
===Library gonum/matrix===
Gonum/matrix doesn't have the Kronecker product, but here's an implementation using available methods.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,552 ⟶ 2,097:
1, 1, 1, 1,
}))))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,572 ⟶ 2,117:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (transpose)
 
-------------------- KRONECKER PRODUCT -------------------
kprod
:: Num a
=> [[a]] -> [[a]] -> [[a]]
kprod xs ys =
let f = fmap . fmap . (*) -- Multiplication by n over list of lists
in fmap concat . transpose =<< fmap (`f` ys) <$> xs
 
kroneckerProduct :: Num a => [[a]] -> [[a]] -> [[a]]
kroneckerProduct xs ys =
fmap (`f` ys) <$> xs
>>= fmap concat . transpose
where
f = fmap . fmap . (*)
 
 
--------------------------- TEST -------------------------
main :: IO ()
main = do
mapM_
mapM_ print $ kprod [[1, 2], [3, 4]] [[0, 5], [6, 7]]
print
putStrLn []
( kroneckerProduct
mapM_ print $
[[1, 2], [3, 4]]
kprod
[[0, 1, 05], [16, 1, 1], [0, 1, 07]]
)
[[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]]</lang>
>> putStrLn []
>> mapM_
print
( kroneckerProduct
[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
[[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]]
)</syntaxhighlight>
{{Out}}
<pre>[0,5,0,10]
[0,5,0,10]
[6,7,12,14]
[0,15,0,20]
Line 1,612 ⟶ 2,167:
Explicit implementation:
 
<langsyntaxhighlight Jlang="j">KP=: dyad def ',/"2 ,/ 1 3 |: x */ y'</langsyntaxhighlight>
 
Tacit:
 
<langsyntaxhighlight Jlang="j">KP=: 1 3 ,/"2@(,/)@|: */</langsyntaxhighlight>
 
these definitions are functionally equivalent.
Line 1,622 ⟶ 2,177:
Task examples:
 
<langsyntaxhighlight Jlang="j"> M=: 1+i.2 2
N=: (+4**)i.2 2
P=: -.0 2 6 8 e.~i.3 3
Line 1,640 ⟶ 2,195:
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</langsyntaxhighlight>
 
=={{header|Java}}==
 
<syntaxhighlight lang="java">
<lang Java>
package kronecker;
 
Line 1,789 ⟶ 2,344:
 
}
</syntaxhighlight>
</lang>
 
{{Output}}
Line 1,838 ⟶ 2,393:
====Version #1.====
{{Works with|Chrome}}
<langsyntaxhighlight lang="javascript">
// matkronprod.js
// Prime function:
Line 1,856 ⟶ 2,411:
}
}
</langsyntaxhighlight>
 
;Required tests:
<langsyntaxhighlight lang="html">
<!-- KronProdTest.html -->
<html><head>
Line 1,878 ⟶ 2,433:
</head><body></body>
</html>
</langsyntaxhighlight>
{{Output}} '''Console and page results'''
<pre>
Line 1,918 ⟶ 2,473:
{{trans|PARI/GP}}
{{Works with|Chrome}}
<langsyntaxhighlight lang="javascript">
// matkronprod2.js
// Prime function:
Line 1,949 ⟶ 2,504:
}
}
</langsyntaxhighlight>
;Required tests:
<langsyntaxhighlight lang="html">
<!-- KronProdTest2.html -->
<html><head>
Line 1,970 ⟶ 2,525:
</head><body></body>
</html>
</langsyntaxhighlight>
 
{{Output}} '''Console and page results'''
Line 1,981 ⟶ 2,536:
{{Trans|Haskell}}
(As JavaScript is now widely embedded in non-browser contexts, a non-HTML string value is returned here, rather than making calls to methods of the Document Object Model, which is not part of JavaScript and will not always be available to a JavaScript interpreter)
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 2,067 ⟶ 2,622:
// MAIN ---
console.log(main());
})();</langsyntaxhighlight>
{{Out}}
<pre>[0,5,0,10]
Line 2,086 ⟶ 2,641:
=={{header|jq}}==
In this entry, matrices are JSON arrays of numeric arrays. For the sake of illustration, the ancillary functions, though potentially independently useful, are defined here as inner functions.
<langsyntaxhighlight lang="jq">def kprod(a; b):
 
# element-wise multiplication of a matrix by a number, "c"
Line 2,103 ⟶ 2,658:
| reduce range(0; a|length) as $i ([];
. + reduce range(0; $m) as $j ([];
addblock( b | multiply(a[$i][$j]) ) ));</langsyntaxhighlight>
 
Examples:
<syntaxhighlight lang="jq">
<lang jq>
def left: [[ 1, 2], [3, 4]];
def right: [[ 0, 5], [6, 7]];
 
kprod(left;right)</langsyntaxhighlight>
{{out}}
<pre>[[0,5,0,10],[6,7,12,14],[0,15,0,20],[18,21,24,28]]</pre>
 
<syntaxhighlight lang="jq">
<lang jq>
def left: [[0, 1, 0], [1, 1, 1], [0, 1, 0]];
def right: [[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]];
 
kprod(left;right)</langsyntaxhighlight>
{{out}}
<pre>[[0,0,0,0,1,1,1,1,0,0,0,0],
Line 2,132 ⟶ 2,687:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia"># v0.6
 
# Julia has a builtin kronecker product function
Line 2,150 ⟶ 2,705:
for row in 1:size(k)[1]
println(k[row,:])
end</langsyntaxhighlight>
 
{{out}}
Line 2,172 ⟶ 2,727:
=={{header|Kotlin}}==
{{trans|JavaScript (Imperative #2)}}
<langsyntaxhighlight lang="scala">// version 1.1.2 (JVM)
 
typealias Matrix = Array<IntArray>
Line 2,231 ⟶ 2,786:
r = kroneckerProduct(a, b)
printAll(a, b, r)
}</langsyntaxhighlight>
 
{{out}}
Line 2,272 ⟶ 2,827:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
function prod( a, b )
print( "\nPRODUCT:" )
Line 2,292 ⟶ 2,847:
b = { { 1, 1, 1, 1 }, { 1, 0, 0, 1 }, { 1, 1, 1, 1 } }
prod( a, b )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,313 ⟶ 2,868:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">KroneckerProduct[{{1, 2}, {3, 4}}, {{0, 5}, {6, 7}}]//MatrixForm
 
KroneckerProduct[{{0, 1, 0}, {1, 1, 1}, {0, 1, 0}},
{{1, 1, 1, 1}, {1, 0, 0, 1}, {1, 1, 1, 1}}]//MatrixForm</langsyntaxhighlight>
 
{{out}}
<pre>0 5 0 10
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
Line 2,335 ⟶ 2,886:
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>
 
=={{header|Maxima}}==
There is a built-in function kronecker autoloaded from linearalgebra package.
 
Here comes a naive implementation.
<syntaxhighlight lang="maxima">
 
/* Function to map first, second and so on, over a list of lists without recurring corresponding built-in functions */
auxkron(n,lst):=makelist(lst[k][n],k,1,length(lst));
 
/* Function to subdivide a list into lists of equal lengths */
lst_equally_subdivided(lst,n):=if mod(length(lst),n)=0 then makelist(makelist(lst[i],i,j,j+n-1),j,1,length(lst)-1,n);
 
/* Kronecker product implementation */
alternative_kronecker(MatA,MatB):=block(auxlength:length(first(args(MatA))),makelist(i*args(MatB),i,flatten(args(MatA))),
makelist(apply(matrix,%%[i]),i,1,length(%%)),
lst_equally_subdivided(%%,auxlength),
makelist(map(args,%%[i]),i,1,length(%%)),
makelist(auxkron(j,%%),j,1,auxlength),
makelist(apply(append,%%[i]),i,1,length(%%)),
apply(matrix,%%),
transpose(%%),
args(%%),
makelist(apply(append,%%[i]),i,1,length(%%)),
apply(matrix,%%));
</syntaxhighlight>
 
Another implementation that does not make use of auxkron
<syntaxhighlight lang="maxima">
altern_kronecker(MatA,MatB):=block(auxlength:length(first(args(MatA))),
makelist(i*args(MatB),i,flatten(args(MatA))),
makelist(apply(matrix,%%[i]),i,1,length(%%)),
lst_equally_subdivided(%%,auxlength),
makelist(apply(addcol,%%[i]),i,1,length(%%)),
map(args,%%),
apply(append,%%),
apply(matrix,%%));
</syntaxhighlight>
{{out}}<pre>
A:matrix([0,1,0],[1,1,1],[0,1,0])$
B:matrix([1,1,1,1],[1,0,0,1],[1,1,1,1])$
 
C:matrix([1,2],[3,4])$
D:matrix([0,5],[6,7])$
 
alternative_kronecker(A,B);
/* matrix(
[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]
) */
 
alternative_kronecker(C,D);
/* matrix(
[0, 5, 0, 10],
[6, 7, 12, 14],
[0, 15, 0, 20],
[18, 21, 24, 28]
) */
 
/* altern_kronecker gives the same outputs */
</pre>
 
Line 2,341 ⟶ 2,959:
Same as Kotlin but with a generic Matrix type.
 
<langsyntaxhighlight Nimlang="nim">import strutils
 
type Matrix[M, N: static Positive; T: SomeNumber] = array[M, array[N, T]]
Line 2,379 ⟶ 2,997:
echo "Matrix A:\n", A2
echo "Matrix B:\n", B2
echo "Kronecker product:\n", kroneckerProduct(A2, B2)</langsyntaxhighlight>
 
{{out}}
Line 2,418 ⟶ 3,036:
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">>> kron([1 2; 3 4], [0 5; 6 7])
ans =
 
Line 2,437 ⟶ 3,055:
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</langsyntaxhighlight>
 
=={{header|ooRexx}}==
{{trans|REXX}}
<syntaxhighlight lang="oorexx">/*REXX program multiplies two matrices together, */
/* displays the matrices and the result. */
Signal On syntax
amat=2x2 1 2 3 4 /* define A matrix size and elements */
bmat=2x2 0 5 6 7 /* " B " " " " */
a=.matrix~new('A',2,2,1 2 3 4) /* create matrix A */
b=.matrix~new('B',2,2,0 5 6 7) /* create matrix B */
a~show
b~show
c=kronmat(a,b)
c~show
Say ''
Say copies('|',55)
Say ''
a=.matrix~new('A',3,3,0 1 0 1 1 1 0 1 0) /* create matrix A */
b=.matrix~new('B',3,4,1 1 1 1 1 0 0 1 1 1 1 1) /* create matrix B */
a~show
b~show
c=kronmat(a,b)
c~show
Exit
 
kronmat: Procedure /* compute the Kronecker Product */
Use Arg a,b
rp=0 /* row of product */
Do ra=1 To a~rows
Do rb=1 To b~rows
rp=rp+1 /* row of product */
cp=0 /* column of product */
Do ca=1 To a~cols
x=a~element(ra,ca)
Do cb=1 To b~cols
y=b~element(rb,cb)
cp=cp+1 /* column of product */
xy=x*y
c.rp.cp=xy /* element of product */
End /* cb */
End /* ca */
End /* rb */
End /* ra */
mm=''
Do i=1 To a~rows*b~rows
Do j=1 To a~rows*b~cols
mm=mm C.i.j
End /*j*/
End /*i*/
c=.matrix~new('Kronecker product',a~rows*b~rows,a~rows*b~cols,mm)
Return c
/*--------------------------------------------------------------------*/
Exit:
Say arg(1)
Exit
Syntax:
Say 'Syntax raised in line' sigl
Say sourceline(sigl)
Say 'rc='rc '('errortext(rc)')'
Say '***** There was a problem!'
Exit
 
::class Matrix
/********************************************************************
* Matrix is implemented as an array of rows
* where each row is an arryay of elements.
********************************************************************/
::Attribute name
::Attribute rows
::Attribute cols
 
::Method init
expose m name rows cols
Use Arg name,rows,cols,elements
If words(elements)<>(rows*cols) Then Do
Say 'incorrect number of elements ('words(elements)')<>'||(rows*cols)
m=.nil
Return
End
m=.array~new
Do r=1 To rows
ro=.array~new
Do c=1 To cols
Parse Var elements e elements
ro~append(e)
End
m~append(ro)
End
 
::Method element /* get an element's value */
expose m
Use Arg r,c
ro=m[r]
Return ro[c]
 
::Method set /* set an element's value and return its previous */
expose m
Use Arg r,c,new
ro=m[r]
old=ro[c]
ro[c]=new
Return old
 
::Method show public /* display the matrix */
expose m name rows cols
z='+'
b6=left('',6)
Say ''
Say b6 copies('-',7) 'matrix' name copies('-',7)
w=0
Do r=1 To rows
ro=m[r]
Do c=1 To cols
x=ro[c]
w=max(w,length(x))
End
End
Say b6 b6 '+'copies('-',cols*(w+1)+1)'+' /* top border */
Do r=1 To rows
ro=m[r]
line='|' right(ro[1],w) /* element of first colsumn */ /* start with long vertical bar */
Do c=2 To cols /* loop for other columns */
line=line right(ro[c],w) /* append the elements */
End /* c */
Say b6 b6 line '|' /* append a long vertical bar. */
End /* r */
Say b6 b6 '+'copies('-',cols*(w+1)+1)'+' /* bottom border */
Return</syntaxhighlight>
{{out|output}}
<pre>
------- matrix A -------
+-----+
| 1 2 |
| 3 4 |
+-----+
 
------- matrix B -------
+-----+
| 0 5 |
| 6 7 |
+-----+
 
------- matrix Kronecker product -------
+-------------+
| 0 5 0 10 |
| 6 7 12 14 |
| 0 15 0 20 |
| 18 21 24 28 |
+-------------+
 
|||||||||||||||||||||||||||||||||||||||||||||||||||||||
 
 
------- matrix A -------
+-------+
| 0 1 0 |
| 1 1 1 |
| 0 1 0 |
+-------+
 
------- matrix B -------
+---------+
| 1 1 1 1 |
| 1 0 0 1 |
| 1 1 1 1 |
+---------+
 
------- matrix Kronecker product -------
+-------------------------+
| 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>
 
 
=={{header|PARI/GP}}==
=== Version #1 ===
{{Works with|PARI/GP|2.9.1 and above}}
<langsyntaxhighlight lang="parigp">
\\ Print title and matrix mat rows. 4/17/16 aev
matprows(title,mat)={print(title); for(i=1,#mat[,1], print(mat[i,]))}
Line 2,470 ⟶ 3,268:
matprows("Sample 2 result:",r);
}
</langsyntaxhighlight>
{{Output}}
Line 2,493 ⟶ 3,291:
This version is from B. Allombert. 12/12/17
{{Works with|PARI/GP|2.9.1 and above}}
<langsyntaxhighlight lang="parigp">
\\ Print title and matrix mat rows. aev
matprows(title,mat)={print(title); for(i=1,#mat[,1], print(mat[i,]))}
Line 2,512 ⟶ 3,310:
matprows("Sample 2 result:",r);
}
</langsyntaxhighlight>
{{Output}}
Line 2,534 ⟶ 3,332:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
use strict;
use warnings;
use PDL;
use PDL::NiceSlice;
 
sub kron {
my ($x, $Ay) = shift@_;
 
my $B = shift;
return $x->dummy(0)
my ($r0, $c0) = $A->dims;
->dummy(0)
my ($r1, $c1) = $B->dims;
->mult($y, 0)
my $kron = zeroes($r0 * $r1, $c0 * $c1);
->clump(0, 2)
for(my $i = 0; $i < $r0; ++$i){
->clump(1, 2)
for(my $j = 0; $j < $c0; ++$j){
$kron(
($i * $r1) : (($i + 1) * $r1 - 1),
($j * $c1) : (($j + 1) * $c1 - 1)
) .= $A($i,$j) * $B;
}
}
return $kron;
}
 
my @mats = (
[pdl([[1, 2], [3, 4]]), pdl([[0,5], [6,7]])],
[pdl([[0,1,0], [1,1,1], [0,1,0]]), pdl([[10,1,1,1 5], [1,0,0,1]6, [1,1,1,17]])],
[pdl([[0, 1, 0], [1, 1, 1], [0, 1, 0]]),
pdl([[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]])],
);
for my $mat (@mats) {
print "A = $mat->[0]\n";
print "B = $mat->[1]\n";
print "kron(A,B) = " . kron($mat->[0], $mat->[1]) . "\n";
}</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">kronecker</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ar</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">),</span>
Line 2,604 ⟶ 3,396:
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">kronecker</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">),{</span><span style="color: #004600;">pp_Nest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_IntFmt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%2d"</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">kronecker</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">),{</span><span style="color: #004600;">pp_Nest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,621 ⟶ 3,413:
{0,0,0,0,1,1,1,1,0,0,0,0}}
</pre>
 
=={{header|Pike}}==
{{trans|Python}}
 
<syntaxhighlight lang="pike">array kronecker(array matrix1, array matrix2) {
array final_list = ({});
array sub_list = ({});
 
int count = sizeof(matrix2);
 
foreach(matrix1, array elem1) {
int counter = 0;
int check = 0;
while (check < count) {
foreach(elem1, int num1) {
foreach(matrix2[counter], int num2) {
sub_list = Array.push(sub_list, num1 * num2);
}
}
counter += 1;
final_list = Array.push(final_list, sub_list);
sub_list = ({});
check += 1;
}
}
 
return final_list;
}
 
int main() {
//Sample 1
array(array(int)) a1 = ({ ({1, 2}), ({3, 4}) });
array(array(int)) b1 = ({ ({0, 5}), ({6, 7}) });
//Sample 2
array(array(int)) a2 = ({ ({0, 1, 0}), ({1, 1, 1}), ({0, 1, 0}) });
array(array(int)) b2 = ({ ({1, 1, 1, 1}), ({1, 0, 0, 1}), ({1, 1, 1, 1}) });
 
array result1 = kronecker(a1, b1);
for (int i = 0; i < sizeof(result1); i++) {
foreach(result1[i], int result) {
write((string)result + " ");
}
write("\n");
}
 
write("\n");
 
array result2 = kronecker(a2, b2);
for (int i = 0; i < sizeof(result2); i++) {
foreach(result2[i], int result) {
write((string)result + " ");
}
write("\n");
}
 
return 0;
}</syntaxhighlight>
{{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>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
DataSection
Matrix_A_B_Dimension_Bsp1:
Line 2,730 ⟶ 3,595:
Bsp2_Matrix_A_B:
Restore Matrix_A_B_Dimension_Bsp2
Return</langsyntaxhighlight>
{{out}}
<pre>Matrix A:
Line 2,773 ⟶ 3,638:
In Python, the numpy library has the [https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.kron.html kron] function. The following is an implementation for "bare" lists of lists.
 
<langsyntaxhighlight Pythonlang="python">#!/usr/bin/env python3
 
# Sample 1
Line 2,813 ⟶ 3,678:
result2 = kronecker(a2, b2)
for elem in result2:
print(elem)</langsyntaxhighlight>
 
Result:
Line 2,836 ⟶ 3,701:
 
Code:
<langsyntaxhighlight Pythonlang="python"># Sample 1
r = [[1, 2], [3, 4]]
s = [[0, 5], [6, 7]]
Line 2,854 ⟶ 3,719:
# Result 2
for row in kronecker(t, u):
print(row)</langsyntaxhighlight>
 
===Version 3===
Line 2,866 ⟶ 3,731:
 
(Versions 2 and 3 produce the same output from the same test)
<langsyntaxhighlight lang="python">from itertools import (chain)
 
 
Line 2,911 ⟶ 3,776:
# Result 2
for row in kronecker(t, u):
print(row)</langsyntaxhighlight>
{{Out}}
<pre>[0, 5, 0, 10]
Line 2,930 ⟶ 3,795:
=={{header|R}}==
R has built-in Kronecker product operator for a and b matrices: '''a %x% b'''.
<syntaxhighlight lang="r">
<lang r>
## Sample using:
a <- matrix(c(1,1,1,1), ncol=2, nrow=2, byrow=TRUE);
b <- matrix(c(0,1,1,0), ncol=2, nrow=2, byrow=TRUE);
a %x% b
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 2,951 ⟶ 3,816:
Uses typed racket, since the 'math/...' libraries are much more performant in that language.
 
<langsyntaxhighlight lang="racket">#lang typed/racket/base
 
(require math/array
Line 2,983 ⟶ 3,848:
(matrix [[1 1 1 1]
[1 0 0 1]
[1 1 1 1]])))</langsyntaxhighlight>
 
{{out}}
Line 3,001 ⟶ 3,866:
(formerly Perl 6)
{{works with|rakudo|2017.01-34-g700a077}}
<syntaxhighlight lang="raku" perl6line>sub kronecker_product ( @a, @b ) {
return (@a X @b).map: { .[0].list X* .[1].list };
}
Line 3,010 ⟶ 3,875:
.say for kronecker_product([ <0 1 0>, <1 1 1>, <0 1 0> ],
[ <1 1 1 1>, <1 0 0 1>, <1 1 1 1>]);
</syntaxhighlight>
</lang>
{{out}}
<pre>(0 5 0 10)
Line 3,029 ⟶ 3,894:
=={{header|REXX}}==
A little extra coding was added to make the matrix glyphs and elements alignment look nicer.
<langsyntaxhighlight lang="rexx">/*REXX program calculates the Kronecker product of two matrices. two arbitrary size matrices. */
w= 0 /* W: max width of any matrix element. */
aMatamat= 2x2 1 2 3 4 /* define A matrix size and elements. */
bMatbmat= 2x2 0 5 6 7 /* " " B " " " " */
callCall makeMat 'A', aMat amat /* construct A matrix from elements. */
callCall makeMat 'B', bMat bmat /* " " B " " " */
callCall KronMat 'Kronecker product' /* calculate the Kronecker product. */
Call showMat what,arows*brows||'X'||arows*bcols
w= 0; say; say copies('░', 55); say /*display a fence between the 2 outputs*/
Say ''
aMat= 3x3 0 1 0 1 1 1 0 1 0 /*define A matrix size and elements.*/
Say copies('|',55)
bMat= 3x4 1 1 1 1 1 0 0 1 1 1 1 1 /* " B " " " " */
Say ''
call makeMat 'A', aMat /*construct A matrix from elements.*/
callw=0 makeMat 'B', bMat /* W: max width " B " " " of any matrix element*/
call KronMat 'Kronecker product' amat=3x3 0 1 0 1 1 1 0 1 0 /*calculate the define KroneckerA matrix product.size and elements */
exitbmat=3x4 1 1 1 1 1 0 0 1 1 1 1 1 /* " B " " " " /*stick a fork in it, we're all done. */
Call makeMat 'A',amat /* construct A matrix from elements */
/*──────────────────────────────────────────────────────────────────────────────────────*/
KronMat:Call parsemakeMat arg'B',bmat what; /* " parse var @.a.shapeB aRows aCols" " " */
Call KronMat 'Kronecker product' /* calculate the Kronecker product */
#= 0; parse var @.b.shape bRows bCols
Call showMat what,arows*brows||'X'||arows*bcols
do rA=1 for aRows
Exit do rB=1 for bRows; #= #+1; /* stick a fork in it, we're all ##= 0; _=done*/
/*--------------------------------------------------------------------*/
do cA=1 for aCols; x= @.a.rA.cA
makemat:
do cB=1 for bCols; y= @.b.rB.cB; ##= ##+1; xy= x*y; _= _ xy
Parse Arg what,size elements /*elements: e.1.1 e.1.2 - e.rows cols*/
@.what.#.##=xy; w= max(w, length(xy) )
Parse Var size rows 'X' cols
end /*cB*/
x.what.shape=rows cols
end /*cA*/
n=0
end /*rB*/
Do r=1 To rows
end /*rA*/
Do c=1 To cols
call showMat what, aRows*bRows || 'X' || aRows*bCols; return
n=n+1
/*──────────────────────────────────────────────────────────────────────────────────────*/
element=word(elements,n)
makeMat: parse arg what, size elements; arg , row 'X' col .; @.what.shape=row col
w=max(w,length(element))
#=0; do r=1 for row /* [↓] bump item#; get item; max width*/
x.what.r.c=element
do c=1 for col; #= #+1; _= word(elements, #); w= max(w, length(_))
End
@.what.r.c=_
End
end /*c*/ /* [↑] define an element of WHAT matrix*/
Call showMat what,size
end /*r*/
Return
call showMat what, size; return
/*--------------------------------------------------------------------*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
kronmat: /* compute the Kronecker Product */
showMat: parse arg what, size .; z= '┌'; parse var size row "X" col; $=left('', 6)
Parse Arg what
say; say $ copies('═',7) "matrix" what copies('═',7)
Parse Var x.a.shape arows acols
do r=1 for row; _= '│' /*start with long vertical bar*/
Parse Var x.b.shape brows bcols
do c=1 for col; _=_ right(@.what.r.c, w); if r==1 then z=z left('',w)
rp=0 end /*c row of product */
Do ra=1 To arows
if r==1 then do; z=z '┐'; say $ $ z; end /*show the top part of matrix.*/
Do rb=1 To brows
say $ $ _ '│' /*append a long vertical bar. */
rp=rp+1 end /*r row of product */
cp=0 say $ $ translate(z, '└┘', "┌┐"); return /*show thecolumn of product bot part of matrix.*/</lang>
Do ca=1 To acols
x=x.a.ra.ca
Do cb=1 To bcols
y=x.b.rb.cb
cp=cp+1 /* column of product */
xy=x*y
x.what.rp.cp=xy /* element of product */
w=max(w,length(xy))
End /* cB */
End /* cA */
End /* rB */
End /* rA */
Return
/*--------------------------------------------------------------------*/
showmat:
Parse Arg what,size .
Parse Var size rows 'X' cols
z='+'
b6=left('',6)
Say ''
Say b6 copies('-',7) 'matrix' what copies('-',7)
Say b6 b6 '+'copies('-',cols*(w+1)+1)'+'
Do r=1 To rows
line='|' right(x.what.r.1,w) /* element of first column */ /* start with long vertical bar */
Do c=2 To cols /* loop for other columns */
line=line right(x.what.r.c,w) /* append the elements */
End /* c */
Say b6 b6 line '|' /* append a long vertical bar. */
End /* r */
Say b6 b6 '+'copies('-',cols*(w+1)+1)'+'
Return
</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
═══════------- matrix A ═══════-------
┌ ┐+-----+
| 1 2 |
| 3 4 |
└ ┘+-----+
 
═══════------- matrix B ═══════-------
┌ ┐+-----+
| 0 5 |
| 6 7 |
└ ┘+-----+
 
═══════------- matrix Kronecker product ═══════-------
┌ ┐+-------------+
| 0 5 0 10 |
| 6 7 12 14 |
| 0 15 0 20 |
| 18 21 24 28 |
└ ┘+-------------+
 
|||||||||||||||||||||||||||||||||||||||||||||||||||||||
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 
 
═══════------- matrix A ═══════-------
┌ ┐+-------+
| 0 1 0 |
| 1 1 1 |
| 0 1 0 |
└ ┘+-------+
 
═══════------- matrix B ═══════-------
┌ ┐+---------+
| 1 1 1 1 |
| 1 0 0 1 |
| 1 1 1 1 |
└ ┘+---------+
 
═══════------- matrix Kronecker product ═══════-------
┌ ┐+-------------------------+
| 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>
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Kronecker product
 
Line 3,174 ⟶ 4,070:
next
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,193 ⟶ 4,089:
</pre>
 
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
≪ DUP SIZE LIST→ DROP 4 ROLL DUP SIZE LIST→ DROP → b p q a m n
≪ {} m p * + n q * + 0 CON
1 m p * '''FOR''' row
1 n q * '''FOR''' col
a {} row 1 - p / IP 1 + + col 1 - q / IP 1 + + GET
b {} row 1 - p MOD 1 + + col 1 - q MOD 1 + + GET
* {} row + col + SWAP PUT
'''NEXT NEXT'''
≫ ≫ '<span style="color:blue">KROKR</span>' STO
====HP-49 version====
≪ DUP SIZE LIST→ DROP 4 PICK SIZE LIST→ DROP → a b rb cb ra ca
≪ a SIZE b SIZE * 0 CON
0 ra 1 - '''FOR''' j
0 ca 1 - '''FOR''' k
{ 1 1 }
{ } j + k +
DUP2 ADD a SWAP GET UNROT
{ } ra + ca + * ADD
SWAP b * REPL
'''NEXT NEXT'''
≫ ≫ '<span style="color:blue">KROKR</span>' STO
 
[[1, 2], [3, 4]] [[0, 5], [6, 7]] <span style="color:blue">KROKR</span>
[[0, 1, 0], [1, 1, 1], [0, 1, 0]] [[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]] <span style="color:blue">KROKR</span>
{{out}}
<pre>
2: [[ 0 5 0 10 ]
[ 6 7 12 14 ]
[ 0 15 0 20 ]
[ 18 21 24 28 ]]
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 ]
[ 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>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn main() {
 
let mut a = vec![vec![1., 2.], vec![3., 4.]];
Line 3,288 ⟶ 4,227:
matrix
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,339 ⟶ 4,278:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala"> object KroneckerProduct
{
/**Get the dimensions of the input matrix*/
Line 3,380 ⟶ 4,319:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,401 ⟶ 4,340:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func kronecker_product(a, b) {
a ~X b -> map { _[0] ~X* _[1] }
}
Line 3,410 ⟶ 4,349:
say ''
kronecker_product([[0,1,0], [1,1,1], [0,1,0]],
[[1,1,1,1],[1,0,0,1], [1,1,1,1]]).each { .say }</langsyntaxhighlight>
{{out}}
<pre>
Line 3,430 ⟶ 4,369:
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
 
PROCEDURE OUTMATRIX(A, W); INTEGER ARRAY A; INTEGER W;
Line 3,580 ⟶ 4,519:
 
END EXAMPLE 2;
END</langsyntaxhighlight>
{{out}}
<pre>
Line 3,618 ⟶ 4,557:
In Mata, the Kronecker product is the operator '''#'''.
 
<langsyntaxhighlight lang="stata">. mata
------------------------------------------------- mata (type end to exit) ----------
: a=1,2\3,4
Line 3,650 ⟶ 4,589:
9 | 0 0 0 0 1 1 1 1 0 0 0 0 |
+-------------------------------------------------------------+
: end</langsyntaxhighlight>
 
=={{header|SuperCollider}}==
<langsyntaxhighlight SuperColliderlang="supercollider">// the iterative version is derived from the javascript one here:
(
f = { |a, b|
Line 3,692 ⟶ 4,631:
(a *.2 b).collect(_.reduce('+++')).reduce('++')
 
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight SuperColliderlang="supercollider">// to apply either of the two functions:
(
x = f.(
Line 3,709 ⟶ 4,648:
)
)
</syntaxhighlight>
</lang>
 
Results in:
Line 3,729 ⟶ 4,668:
And:
 
<syntaxhighlight lang="supercollider">(
<lang SuperCollider>(
x = f.(
[
Line 3,741 ⟶ 4,680:
)
)
</syntaxhighlight>
</lang>
 
returns:
Line 3,755 ⟶ 4,694:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">func kronecker(m1: [[Int]], m2: [[Int]]) -> [[Int]] {
let m = m1.count
let n = m1[0].count
Line 3,832 ⟶ 4,771:
]
 
printProducts(a: a2, b: b2)</langsyntaxhighlight>
 
{{out}}
Line 3,868 ⟶ 4,807:
 
=={{header|Tcl}}==
<langsyntaxhighlight Tcllang="tcl"># some helpers for matrices in nice string form:
proc parse_matrix {s} {
split [string trim $s] \n
Line 3,932 ⟶ 4,871:
print_matrix [kroenecker $a $b]
puts ""
}</langsyntaxhighlight>
 
{{out}}
Line 3,952 ⟶ 4,891:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">' Kronecker product - 05/04/2017 ' array boundary iteration corrections 06/13/2023
dim a(),b(),r()
Line 3,969 ⟶ 4,908:
end sub 'kroneckerproduct
subPrivate Sub printmatrix(text, m, w)
wscript.stdout.writeline text
selectDim case mmyArr()
Select Case m
case "a": ni=ubound(a,1): nj=ubound(a,2)
caseCase "ba": nimyArr =ubound(b,1): nj=ubounda(b,2)
caseCase "rb": nimyArr =ubound(r,1): nj=uboundb(r,2)
Case "r": myArr = r()
end select
forEnd i=1 to niSelect
For i = LBound(myArr, for j=1) toTo njUBound(myArr, 1)
text = select case mvbNullString
For j = LBound(myArr, 2) To case "a": k=aUBound(imyArr,j 2)
Select Case case "b": k=b(i,j)m
caseCase "ra": k =r a(i, j)
end select Case "b": k = b(i, j)
wscript.stdout.write right(space(w)& Case "r": k = r(i,w j)
next End Select
wscript.stdout.writeline text = text & " " & k
next Next
wscript.stdout.writeline text
end sub 'printmatrix
Next
End Sub 'printmatrix
 
sub printall(w)
printmatrix "matrix a:", "a", w
Line 3,996 ⟶ 4,937:
sub main()
xa =array( Array(1, 2, _
3, 4)
ReDim a(LBound(xa, 1) To LBound(xa, 1) + 1, LBound(xa, 1) To LBound(xa, 1) + 1)
redim a(2,2)
k=0: for i=1 to uboundLBound(a,1): for j=1 to ubound(a,1)
For i = aLBound(ia,j 1)=xa To UBound(ka, 1): kFor j =k+ LBound(a, 1) To UBound(a, 1)
a(i, j) = xa(k): k = k + 1
next:next
Next: Next
xb=array( 0, 5, _
xb = Array(0, 65, 7)_
redim b(2 6,2 7)
k=0:ReDim forb(LBound(xb, i=1) toTo uboundLBound(bxb, 1): for+ j=1, toLBound(xb, 1) To uboundLBound(bxb, 1) + 1)
k = LBound(b(i,j)=xb(k): k=k+1)
For i = LBound(b, 1) To UBound(b, 1): For j = LBound(b, 2) To UBound(b, 2)
next:next
b(i, j) = xb(k): k = k + 1
Next: Next
kroneckerproduct
printall 3
 
xa =array( Array(0, 1, 0, _
1, 1, 1, _
0, 1, 0)
ReDim a(LBound(xa, 1) To LBound(xa, 1) + 2, LBound(xa, 1) To LBound(xa, 1) + 2)
redim a(3,3)
k=0: for i=1 to uboundLBound(a,1): for j=1 to ubound(a,1)
For i = aLBound(ia,j 1)=xa To UBound(ka, 1): kFor j =k+ LBound(a, 1) To UBound(a, 1)
a(i, j) = xa(k): k = k + 1
next:next
Next: Next
xb=array( 1, 1, 1, 1, _
xb = Array(1, 01, 01, 1, _
1, 10, 10, 1), _
redim b(3 1,4 1, 1, 1)
k=0:ReDim forb(LBound(xb, i=1) toTo uboundLBound(bxb, 1): for+ 2, LBound(xb, j=1) toTo uboundLBound(bxb, 1) + 3)
k = LBound(b(i,j)=xb(k): k=k+1)
For i = LBound(b, 1) To UBound(b, 1): For j = LBound(b, 2) To UBound(b, 2)
next:next
b(i, j) = xb(k): k = k + 1
Next: Next
 
kroneckerproduct
printall 2
end sub 'main
 
main</langsyntaxhighlight>
{{out}}
<pre>
Line 4,043 ⟶ 4,989:
0 15 0 20
18 21 24 28
 
matrix a:
0 1 0
Line 4,048 ⟶ 4,995:
0 1 0
matrix b:
1 1 1 1
1 10 0 1
01 1 1 1
kronecker product:
0 0 0 0 1 1 1 01 0 0 0 0
0 0 0 0 1 1 0 0 1 0 0 0 0
0 0 0 0 01 1 1 01 0 0 0 0
1 1 1 01 1 1 1 01 1 1 1 01
1 1 0 0 1 1 0 0 1 1 0 0 1
01 1 1 01 01 1 1 01 01 1 1 01
0 0 0 0 1 1 1 01 0 0 0 0
0 0 0 0 1 1 0 0 1 0 0 0 0
0 0 0 0 01 1 1 01 0 0 0 0
</pre>
 
Line 4,067 ⟶ 5,014:
{{libheader|Wren-matrix}}
The above module already includes a method to calculate the Kronecker product.
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
import "./matrix" for Matrix
 
var a1 = [
Line 4,098 ⟶ 5,045:
var m3 = Matrix.new(a3)
var m4 = Matrix.new(a4)
Fmt.mprint(m3.kronecker(m4), 2, 0)</langsyntaxhighlight>
 
{{out}}
Line 4,119 ⟶ 5,066:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">var [const] GSL=Import.lib("zklGSL"); // libGSL (GNU Scientific Library)
fcn kronecker(A,B){
m,n, p,q := A.rows,A.cols, B.rows,B.cols;
Line 4,125 ⟶ 5,072:
foreach i,j,k,l in (m,n,p,q){ r[p*i + k, q*j + l]=A[i,j]*B[k,l] }
r
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">A:=GSL.Matrix(2,2).set(1,2, 3,4);
B:=GSL.Matrix(2,2).set(0,5, 6,7);
kronecker(A,B).format(3,0).println(); // format(width,precision)
Line 4,136 ⟶ 5,083:
1,0,0,1,
1,1,1,1);
kronecker(A,B).format(2,0).println();</langsyntaxhighlight>
{{out}}
<pre>
2,122

edits