Kronecker product: Difference between revisions

Added Yabasic
m (added whitespace to the task's preamble and also before the TOC, changed ;See also: to ;Related task:.)
(Added Yabasic)
 
(123 intermediate revisions by 58 users not shown)
Line 1:
{{task}}{{Wikipedia}}
{{Task|Matrices}}
 
 
;Task:
Implement the &nbsp; [[wp:Kronecker_product| Kronecker product]] &nbsp; of two matrices (arbitrary sized) resulting in a block matrix. <br />
 
 
;Test cases:
Show results for each of the following 2two samples:<br>
 
 
Sample 1 (from Wikipedia):
<pre>
 
|1 2| x |0 5| = | 0 5 0 10|
 
|3 4| |6 7| | 6 7 12 14|
┌ ┐ ┌ ┐ ┌ ┐
| 0 15 0 20|
│1 2│ │0 5│ │ 0 5 0 10│
|18 21 24 28|
│3 4│ x │6 7│ = │ 6 7 12 14│
└ ┘ └ ┘ │ 0 15 0 20│
│18 21 24 28│
└ ┘
</pre>
 
Sample 2:
<pre>
┌ ┐ ┌ ┐ ┌ ┐
|0 1 0| x |1 1 1 1| = |0 0 0 0 1 1 1 1 0 0 0 0|
|1 1 1| | │0 1 00│ 0 │1 1| 1 1│ |0 │0 0 0 0 1 01 01 1 0 0 0 0|0│
|0 1 0| |1 1 1 │1 1| 1│ |x │1 0 0 1│ = │0 0 0 10 1 10 0 1 0 0 0 0|0│
│0 1 0│ |1 1 1 1│1 1 1 11│ 1 │0 0 0 0 1 1 1 1| 0 0 0 0│
|1 0 0│1 1 1 01 01 1 1 01 01 1| 1 1│
|1 1 1 1 1 1 1 1 │1 0 0 1 1 0 0 1 1| 0 0 1│
|0 0 0 0 │1 1 1 1 1 01 01 01 1 1 1 0|1│
|0 │0 0 0 0 1 01 01 1 0 0 0 0|0│
|0 │0 0 0 0 1 10 10 1 0 0 0 0|0│
│0 0 0 0 1 1 1 1 0 0 0 0│
└ ┘
</pre>
 
 
See implementations and results below in JavaScript and PARI/GP languages.
 
Line 36 ⟶ 46:
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V a1 = [[1, 2], [3, 4]]
V b1 = [[0, 5], [6, 7]]
 
V a2 = [[0, 1, 0], [1, 1, 1], [0, 1, 0]]
V b2 = [[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]]
 
F kronecker(matrix1, matrix2)
[[Int]] final_list
[Int] sub_list
V count = matrix2.len
 
L(elem1) matrix1
V counter = 0
V check = 0
L check < count
L(num1) elem1
L(num2) matrix2[counter]
sub_list.append(num1 * num2)
counter++
final_list.append(sub_list)
sub_list.drop()
check++
 
R final_list
 
V result1 = kronecker(a1, b1)
L(elem) result1
print(elem)
 
print(‘’)
 
V result2 = kronecker(a2, b2)
L(elem) result2
print(elem)</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|360 Assembly}}==
<syntaxhighlight lang="360asm">* Kronecker product 06/04/2017
KRONECK CSECT
USING KRONECK,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R1,1 first example
BAL R14,PRODUCT call product(a1,b1)
BAL R14,PRINT call print(r)
XPRNT =C'---',3 separator
LA R1,2 second example
BAL R14,PRODUCT call product(a2,b2)
BAL R14,PRINT call print(r)
L R13,4(0,R13) restore previous savearea pointer
LM R14,R12,12(R13) restore previous context
XR R15,R15 rc=0
BR R14 exit
*------- ---- ----------------------------------------
PRODUCT EQU * product(o)
STC R1,OO store o
IF CLI,OO,EQ,X'01' THEN if o=1 then
MVC MM(8),DIM1 (m,n)=hbound(a1) (p,q)=hbound(b1)
LA R1,A1 @a1
LA R2,B1 @b1
ELSE , else
MVC MM(8),DIM2 (m,n)=hbound(a2) (p,q)=hbound(b2)
LA R1,A2 @a2
LA R2,B2 @b2
ENDIF , endif
ST R1,ADDRA addra=@a1
ST R2,ADDRB addrb=@b1
LH R1,MM m
MH R1,PP p
STH R1,RI ri=m*p
LH R2,NN n
MH R2,QQ *q
STH R2,RJ rj=n*q
LA R6,1 i=1
DO WHILE=(CH,R6,LE,MM) do i=1 to m
LA R7,1 j=1
DO WHILE=(CH,R7,LE,NN) do j=1 to n
LA R8,1 k=1
DO WHILE=(CH,R8,LE,PP) do k=1 to p
LA R9,1 l=1
DO WHILE=(CH,R9,LE,QQ) do l=1 to q
LR R1,R6 i
BCTR R1,0
MH R1,NN *hbound(a,2)
AR R1,R7 j
BCTR R1,0
SLA R1,2
L R4,ADDRA @a
L R2,0(R4,R1) r2=a(i,j)
LR R1,R8 k
BCTR R1,0
MH R1,QQ *hbound(b1,2)
AR R1,R9 l
BCTR R1,0
SLA R1,2
L R4,ADDRB @b
L R3,0(R4,R1) r3=b(k,l)
LR R5,R2 r2
MR R4,R3 *r3
LR R0,R5 r0=a(i,j)*b(k,l)
LR R1,R6 i
BCTR R1,0 i-1
MH R1,PP *p
AR R1,R8 r1=p*(i-1)+k
LR R2,R7 j
BCTR R2,0 j-1
MH R2,QQ *q
AR R2,R9 r2=q*(j-1)+l
BCTR R1,0
MH R1,=AL2(NR) *nr
AR R1,R2 r1=r1+r2
SLA R1,2
ST R0,R-4(R1) r(p*(i-1)+k,q*(j-1)+l)=r0
LA R9,1(R9) l++
ENDDO , enddo l
LA R8,1(R8) k++
ENDDO , enddo k
LA R7,1(R7) j++
ENDDO , enddo j
LA R6,1(R6) i++
ENDDO , enddo i
BR R14 return
*------- ---- ----------------------------------------
PRINT EQU * print
LA R6,1 i
DO WHILE=(CH,R6,LE,RI) do i=1 to ri
MVC PG,=CL80' ' init buffer
LA R10,PG pgi=0
LA R7,1 j
DO WHILE=(CH,R7,LE,RJ) do j=1 to rj
LR R1,R6 i
BCTR R1,0
MH R1,=AL2(NR) *nr
AR R1,R7 +j
SLA R1,2
L R2,R-4(R1) r(i,j)
XDECO R2,XDEC edit
MVC 0(ND,R10),XDEC+12-ND output
LA R10,ND(R10) pgi=pgi+nd
LA R7,1(R7) j++
ENDDO , enddo j
XPRNT PG,L'PG print buffer
LA R6,1(R6) i++
ENDDO , enddo j
BR R14 return
* ---- ----------------------------------------
NR EQU 32 dim result max
ND EQU 3 digits to print
A1 DC F'1',F'2' a1(2,2)
DC F'3',F'4'
B1 DC F'0',F'5' b1(2,2)
DC F'6',F'7'
DIM1 DC H'2',H'2',H'2',H'2' dim a1 , dim b1
A2 DC F'0',F'1',F'0' a2(3,3)
DC F'1',F'1',F'1'
DC F'0',F'1',F'0'
B2 DC F'1',F'1',F'1',F'1' b2(3,4)
DC F'1',F'0',F'0',F'1'
DC F'1',F'1',F'1',F'1'
DIM2 DC H'3',H'3',H'3',H'4' dim a2 , dim b2
ADDRA DS A @a
ADDRB DS A @b
RI DS H ri
RJ DS H rj
MM DS H m
NN DS H n
PP DS H p
QQ DS H q
OO DS X o
PG DS CL80 buffer
XDEC DS CL12
LTORG
R DS (NR*NR)F r(nr,nr)
YREGS
END KRONECK</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|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>
 
=={{header|Ada}}==
 
{{works with|Ada|Ada|83}}
 
<syntaxhighlight lang="ada">with Ada.Text_IO;
with Ada.Integer_Text_IO;
 
procedure Kronecker_Product is
type Matrix is array (Positive range <>, Positive range <>) of Integer;
 
function "*"(Left, Right : in Matrix) return Matrix is
result : Matrix
(1 .. Left'Length(1) * Right'Length(1),
1 .. Left'Length(2) * Right'Length(2));
LI : Natural := 0;
LJ : Natural := 0;
begin
for I in 0 .. result'Length(1) - 1 loop
for J in 0 .. result'Length(2) - 1 loop
result (I + 1, J + 1) :=
Left(Left'First(1) + (LI), Left'First(2) + (LJ))
* Right
(Right'First(1) + (I mod Right'Length(1)),
Right'First(2) + (J mod Right'Length(2)));
if (J+1) mod Right'Length(2) = 0 then
LJ := LJ + 1;
end if;
end loop;
if (I+1) mod Right'Length(1) = 0 then
LI := LI + 1;
end if;
LJ := 0;
end loop;
return result;
end "*";
 
Left1 : constant Matrix := ((1, 2), (3, 4));
Right1 : constant Matrix := ((0, 5), (6, 7));
result1 : constant Matrix := Left1 * Right1;
Left2 : constant Matrix := ((0, 1, 0), (1, 1, 1), (0, 1, 0));
Right2 : constant Matrix := ((1, 1, 1, 1), (1, 0, 0, 1), (1, 1, 1, 1));
result2 : constant Matrix := Left2 * Right2;
begin
for I in result1'Range(1) loop
for J in result1'Range(2) loop
Ada.Integer_Text_IO.Put(Ada.Text_IO.Standard_Output, result1(I, J));
end loop;
Ada.Text_IO.New_Line;
end loop;
 
Ada.Text_IO.New_Line;
 
for I in result2'Range(1) loop
for J in result2'Range(2) loop
Ada.Integer_Text_IO.Put(Ada.Text_IO.Standard_Output, result2(I, J));
end loop;
Ada.Text_IO.New_Line;
end loop;
end Kronecker_Product;</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|ALGOL 68}}==
<syntaxhighlight lang="algol68">BEGIN
# multiplies in-place the elements of the matrix a by the scaler b #
OP *:= = ( REF[,]INT a, INT b )REF[,]INT:
BEGIN
FOR i FROM 1 LWB a TO 1 UPB a DO
FOR j FROM 2 LWB a TO 2 UPB a DO
a[ i, j ] *:= b
OD
OD;
a
END # *:= # ;
# returns the Kronecker Product of the two matrices a and b #
# the result will have lower bounds of 1 #
PRIO X = 6;
OP X = ( [,]INT a, b )[,]INT:
BEGIN
# normalise the matrices to have lower bounds of 1 #
[,]INT l = a[ AT 1, AT 1 ];
[,]INT r = b[ AT 1, AT 1 ];
# construct the result #
INT r 1 size = 1 UPB r;
INT r 2 size = 2 UPB r;
[ 1 : 1 UPB l * 1 UPB r, 1 : 2 UPB l * 2 UPB r ]INT k;
FOR i FROM 1 LWB l TO 1 UPB l DO
FOR j FROM 2 LWB l TO 2 UPB l DO
( k[ 1 + ( ( i - 1 ) * r 1 size ) : i * r 1 size
, 1 + ( ( j - 1 ) * r 2 size ) : j * r 2 size
] := r
) *:= l[ i, j ]
OD
OD;
k
END # X # ;
# prints matrix a with the specified field width #
PROC print matrix = ( [,]INT a, INT field width )VOID:
FOR i FROM 1 LWB a TO 1 UPB a DO
FOR j FROM 2 LWB a TO 2 UPB a DO
print( ( " ", whole( a[ i, j ], field width ) ) )
OD;
print( ( newline ) )
OD # print matrix # ;
# task test cases #
print matrix( [,]INT( ( 1, 2 )
, ( 3, 4 )
)
X [,]INT( ( 0, 5 )
, ( 6, 7 )
)
, -2
);
print( ( newline ) );
print matrix( [,]INT( ( 0, 1, 0 )
, ( 1, 1, 1 )
, ( 0, 1, 0 )
)
X [,]INT( ( 1, 1, 1, 1 )
, ( 1, 0, 0, 1 )
, ( 1, 1, 1, 1 )
)
, -1
)
END
</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|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">kprod ← ⊃ (,/ (⍪⌿ (⊂[3 4] ∘.×)))</syntaxhighlight>
 
{{out}}
 
<pre style="line-height: normal;"> a←2 2⍴ 1 2 3 4
b←2 2⍴ 0 5 6 7
a b (a kprod b)
┌───┬───┬───────────┐
│1 2│0 5│ 0 5 0 10│
│3 4│6 7│ 6 7 12 14│
│ │ │ 0 15 0 20│
│ │ │18 21 24 28│
└───┴───┴───────────┘
x ← 3 3⍴ 0 1 0 1 1 1 0 1 0
y ← 3 4⍴ 1 1 1 1 1 0 0 1 1 1 1 1
x y (x kprod y)
┌─────┬───────┬───────────────────────┐
│0 1 0│1 1 1 1│0 0 0 0 1 1 1 1 0 0 0 0│
│1 1 1│1 0 0 1│0 0 0 0 1 0 0 1 0 0 0 0│
│0 1 0│1 1 1 1│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|AppleScript}}==
<langsyntaxhighlight lang="applescript">------------ KRONECKER PRODUCT OF TWO MATRICES ------------------------------------------
 
-- kprod :: [[Num]] -> [[Num]] -> [[Num]]
on kprod(xs, ys)
script concatTranspose
on lambda|λ|(m)
map(my concat, my transpose(m))
end lambda|λ|
end script
Line 51 ⟶ 632:
-- f :: [[Num]] -> Num -> [[Num]]
on f(mx, n)
script go
on product(a, b)
a * b
end product
on lambda|λ|(xs)
map(curry(product)'s lambda|λ|(n), xs)
end lambda|λ|
end script
map(resultgo, mx)
end f
on lambda|λ|(zs)
map(curry(f)'s lambda|λ|(ys), zs)
end lambda|λ|
end script
Line 72 ⟶ 653:
end kprod
 
-- TEST -------------------------------------------- TEST ---------------------------
on run
unlines(map(show, ¬
Line 84 ⟶ 665:
 
 
-- GENERIC FUNCTIONS ------------------------------------- GENERIC FUNCTIONS ---------------------
 
-- concat :: [[a]] -> [a] | [String] -> String
on concat(xs)
script append
on lambda(a, b)
a & b
end lambda
end script
if length of xs > 0 and class of (item 1 of xs) is string then
set unitacc to ""
else
set unitacc to {}
end if
repeat with i from 1 to length of xs
foldl(append, unit, xs)
set acc to acc & item i of xs
end repeat
acc
end concat
 
 
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
concat(map(f, xs))
set lst to {}
set lng to length of xs
tell mReturn(f)
repeat with i from 1 to lng
set lst to (lst & lambda(contents of item i of xs, i, xs))
end repeat
end tell
return lst
end concatMap
 
 
-- curry :: (Script|Handler) -> Script
on curry(f)
script
on lambda|λ|(a)
script
on lambda|λ|(b)
lambda|λ|(a, b) of mReturn(f)
end lambda|λ|
end script
end lambda|λ|
end script
end curry
 
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
Line 133 ⟶ 707:
set lng to length of xs
repeat with i from 1 to lng
set v to lambda|λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
 
 
-- intercalate :: Text -> [Text] -> Text
Line 146 ⟶ 721:
return strJoined
end intercalate
 
 
-- map :: (a -> b) -> [a] -> [b]
Line 153 ⟶ 729:
set lst to {}
repeat with i from 1 to lng
set end of lst to lambda|λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
 
-- Lift 2nd class handler function into 1st class script wrapper
Line 166 ⟶ 743:
else
script
property lambda|λ| : f
end script
end if
end mReturn
 
 
-- show :: a -> String
Line 176 ⟶ 754:
if c = list then
script serialized
on lambda|λ|(v)
show(v)
end lambda|λ|
end script
Line 184 ⟶ 762:
else if c = record then
script showField
on lambda|λ|(kv)
set {k, v} to kv
k & ":" & show(v)
end lambda|λ|
end script
Line 204 ⟶ 782:
end if
end show
 
 
-- transpose :: [[a]] -> [[a]]
on transpose(xss)
script column
on lambda|λ|(_, iCol)
script row
on lambda|λ|(xs)
item iCol of xs
end lambda|λ|
end script
map(row, xss)
end lambda|λ|
end script
map(column, item 1 of xss)
end transpose
 
 
-- unlines :: [String] -> String
on unlines(xs)
intercalate(linefeed, xs)
end unlines</langsyntaxhighlight>
{{Out}}
<pre>{0, 5, 0, 10}
Line 241 ⟶ 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">
# syntax: GAWK -f KRONECKER_PRODUCT.AWK
BEGIN {
A[++a] = "1 2" ; B[++b] = "0 5"
A[++a] = "3 4" ; B[++b] = "6 7"
main("sample 1",1234)
A[++a] = "0 1 0" ; B[++b] = "1 1 1 1"
A[++a] = "1 1 1" ; B[++b] = "1 0 0 1"
A[++a] = "0 1 0" ; B[++b] = "1 1 1 1"
main("sample 2",3)
exit(0)
}
function main(desc,option) {
#
# option: allows complete flexibility of output; they may be combined
# 1 show A and B matrix
# 2 show A x B
# 3 show product
# 4 show Arow,Acol x Brow,Bcol
#
printf("%s\n\n",desc)
if (option ~ /[1234]/) {
a_rows = show_array(A,"A",option)
b_rows = show_array(B,"B",option)
if (option ~ /2/) { prn("A x B",2) }
if (option ~ /3/) { prn("Product",3) }
if (option ~ /4/) { prn("Arow,Acol x Brow,Bcol",4) }
}
else {
print("nothing to print")
}
print("")
a = b = 0 # reset
delete A
delete B
}
function prn(desc,option, a_cols,b_cols,w,x,y,z,AA,BB) {
printf("%s:\n",desc)
for (w=1; w<=a_rows; w++) {
a_cols = split(A[w],AA," ")
for (x=1; x<=b_rows; x++) {
b_cols = split(B[x],BB," ")
printf("[ ")
for (y=1; y<=a_cols; y++) {
for (z=1; z<=b_cols; z++) {
if (option ~ /2/) { printf("%sx%s ",AA[y],BB[z]) }
if (option ~ /3/) { printf("%2s ",AA[y] * BB[z]) }
if (option ~ /4/) { printf("%s,%sx%s,%s ",w,y,x,z) }
}
}
printf("]\n")
}
}
}
function show_array(arr,desc,option, i,n) {
for (i in arr) {
n++
}
if (option ~ /1/) {
printf("Matrix %s:\n",desc)
for (i=1; i<=n; i++) {
printf("[ %s ]\n",arr[i])
}
}
return(n)
}
</syntaxhighlight>
{{out}}
<pre>
sample 1
 
Matrix A:
[ 1 2 ]
[ 3 4 ]
Matrix B:
[ 0 5 ]
[ 6 7 ]
A x B:
[ 1x0 1x5 2x0 2x5 ]
[ 1x6 1x7 2x6 2x7 ]
[ 3x0 3x5 4x0 4x5 ]
[ 3x6 3x7 4x6 4x7 ]
Product:
[ 0 5 0 10 ]
[ 6 7 12 14 ]
[ 0 15 0 20 ]
[ 18 21 24 28 ]
Arow,Acol x Brow,Bcol:
[ 1,1x1,1 1,1x1,2 1,2x1,1 1,2x1,2 ]
[ 1,1x2,1 1,1x2,2 1,2x2,1 1,2x2,2 ]
[ 2,1x1,1 2,1x1,2 2,2x1,1 2,2x1,2 ]
[ 2,1x2,1 2,1x2,2 2,2x2,1 2,2x2,2 ]
 
sample 2
 
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|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">
#include<stdlib.h>
#include<stdio.h>
 
int main(){
char input[100],output[100];
int i,j,k,l,rowA,colA,rowB,colB,rowC,colC,startRow,startCol;
double **matrixA,**matrixB,**matrixC;
printf("Enter full path of input file : ");
fscanf(stdin,"%s",input);
printf("Enter full path of output file : ");
fscanf(stdin,"%s",output);
FILE* inputFile = fopen(input,"r");
fscanf(inputFile,"%d%d",&rowA,&colA);
matrixA = (double**)malloc(rowA * sizeof(double*));
for(i=0;i<rowA;i++){
matrixA[i] = (double*)malloc(colA*sizeof(double));
for(j=0;j<colA;j++){
fscanf(inputFile,"%lf",&matrixA[i][j]);
}
}
fscanf(inputFile,"%d%d",&rowB,&colB);
matrixB = (double**)malloc(rowB * sizeof(double*));
for(i=0;i<rowB;i++){
matrixB[i] = (double*)malloc(colB*sizeof(double));
for(j=0;j<colB;j++){
fscanf(inputFile,"%lf",&matrixB[i][j]);
}
}
fclose(inputFile);
rowC = rowA*rowB;
colC = colA*colB;
matrixC = (double**)malloc(rowC*sizeof(double*));
for(i=0;i<rowA*rowB;i++){
matrixC[i] = (double*)malloc(colA*colB*sizeof(double));
}
for(i=0;i<rowA;i++){
for(j=0;j<colA;j++){
startRow = i*rowB;
startCol = j*colB;
for(k=0;k<rowB;k++){
for(l=0;l<colB;l++){
matrixC[startRow+k][startCol+l] = matrixA[i][j]*matrixB[k][l];
}
}
}
}
 
FILE* outputFile = fopen(output,"w");
for(i=0;i<rowC;i++){
for(j=0;j<colC;j++){
fprintf(outputFile,"%lf\t",matrixC[i][j]);
}
fprintf(outputFile,"\n");
}
fclose(outputFile);
printf("\n\n\nKronecker product of the two matrices written to %s.",output);
}
</syntaxhighlight>
 
Input file :
<pre>
3 3
0 1 0
1 1 1
0 1 0
3 4
1 1 1 1
1 0 0 1
1 1 1 1
</pre>
 
Console interaction :
<pre>
Enter full path of input file : input3.txt
Enter full path of output file : output3.txt
 
 
 
Kronecker product of the two matrices written to output3.txt.
</pre>
 
Output file :
<pre>
0.000000 0.000000 0.000000 0.000000 1.000000 1.000000 1.000000 1.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 1.000000 0.000000 0.000000 1.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 1.000000 1.000000 1.000000 1.000000 0.000000 0.000000 0.000000 0.000000
1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000
1.000000 0.000000 0.000000 1.000000 1.000000 0.000000 0.000000 1.000000 1.000000 0.000000 0.000000 1.000000
1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000
0.000000 0.000000 0.000000 0.000000 1.000000 1.000000 1.000000 1.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 1.000000 0.000000 0.000000 1.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 1.000000 1.000000 1.000000 1.000000 0.000000 0.000000 0.000000 0.000000
 
</pre>
 
=={{header|C sharp}}==
<syntaxhighlight lang="csharp">using System;
using System.Collections;
using System.Collections.Generic;
using static System.Linq.Enumerable;
 
public static class KroneckerProduct
{
public static void Main() {
int[,] left = { {1, 2}, {3, 4} };
int[,] right = { {0, 5}, {6, 7} };
Print(Multiply(left, right));
 
left = new [,] { {0, 1, 0}, {1, 1, 1}, {0, 1, 0} };
right = new [,] { {1, 1, 1, 1}, {1, 0, 0, 1}, {1, 1, 1, 1} };
Print(Multiply(left, right));
}
 
static int[,] Multiply(int[,] left, int[,] right) {
(int lRows, int lColumns) = (left.GetLength(0), left.GetLength(1));
(int rRows, int rColumns) = (right.GetLength(0), right.GetLength(1));
int[,] result = new int[lRows * rRows, lColumns * rColumns];
 
foreach (var (r, c) in from r in Range(0, lRows) from c in Range(0, lColumns) select (r, c)) {
Copy(r * rRows, c * rColumns, left[r, c]);
}
return result;
void Copy(int startRow, int startColumn, int multiplier) {
foreach (var (r, c) in from r in Range(0, rRows) from c in Range(0, rColumns) select (r, c)) {
result[startRow + r, startColumn + c] = right[r, c] * multiplier;
}
}
}
 
static void Print(int[,] matrix) {
(int rows, int columns) = (matrix.GetLength(0), matrix.GetLength(1));
int width = matrix.Cast<int>().Select(LengthOf).Max();
for (int row = 0; row < rows; row++) {
Console.WriteLine("| " + string.Join(" ", Range(0, columns).Select(column => (matrix[row, column] + "").PadLeft(width, ' '))) + " |");
}
Console.WriteLine();
}
 
private static int LengthOf(int i) {
if (i < 0) return LengthOf(-i) + 1;
int length = 0;
while (i > 0) {
length++;
i /= 10;
}
return length;
}
 
}</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|C++}}==
<syntaxhighlight lang="cpp">#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
 
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<scalar_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
 
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
 
// See https://en.wikipedia.org/wiki/Kronecker_product
template <typename scalar_type>
matrix<scalar_type> kronecker_product(const matrix<scalar_type>& a,
const matrix<scalar_type>& b) {
size_t arows = a.rows();
size_t acolumns = a.columns();
size_t brows = b.rows();
size_t bcolumns = b.columns();
matrix<scalar_type> c(arows * brows, acolumns * bcolumns);
for (size_t i = 0; i < arows; ++i)
for (size_t j = 0; j < acolumns; ++j)
for (size_t k = 0; k < brows; ++k)
for (size_t l = 0; l < bcolumns; ++l)
c(i*brows + k, j*bcolumns + l) = a(i, j) * b(k, l);
return c;
}
 
template <typename scalar_type>
void print(std::wostream& out, const matrix<scalar_type>& a) {
const wchar_t* box_top_left = L"\x250c";
const wchar_t* box_top_right = L"\x2510";
const wchar_t* box_bottom_left = L"\x2514";
const wchar_t* box_bottom_right = L"\x2518";
const wchar_t* box_vertical = L"\x2502";
const wchar_t nl = L'\n';
const wchar_t space = L' ';
const int width = 2;
 
size_t rows = a.rows(), columns = a.columns();
std::wstring spaces((width + 1) * columns, space);
out << box_top_left << spaces << box_top_right << nl;
for (size_t row = 0; row < rows; ++row) {
out << box_vertical;
for (size_t column = 0; column < columns; ++column)
out << std::setw(width) << a(row, column) << space;
out << box_vertical << nl;
}
out << box_bottom_left << spaces << box_bottom_right << nl;
}
 
void test1() {
matrix<int> matrix1(2, 2, {{1,2}, {3,4}});
matrix<int> matrix2(2, 2, {{0,5}, {6,7}});
std::wcout << L"Test case 1:\n";
print(std::wcout, kronecker_product(matrix1, matrix2));
}
 
void test2() {
matrix<int> matrix1(3, 3, {{0,1,0}, {1,1,1}, {0,1,0}});
matrix<int> matrix2(3, 4, {{1,1,1,1}, {1,0,0,1}, {1,1,1,1}});
std::wcout << L"Test case 2:\n";
print(std::wcout, kronecker_product(matrix1, matrix2));
}
 
int main() {
std::wcout.imbue(std::locale(""));
test1();
test2();
return 0;
}</syntaxhighlight>
 
{{out}}
<pre>
Test case 1:
┌ ┐
│ 0 5 0 10 │
│ 6 7 12 14 │
│ 0 15 0 20 │
│18 21 24 28 │
└ ┘
Test case 2:
┌ ┐
│ 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|D}}==
{{Trans|Go}}
<syntaxhighlight lang="d">
import std.stdio, std.outbuffer;
 
alias Matrix = uint[][];
 
string toString(Matrix m) {
auto ob = new OutBuffer();
foreach(row; m) {
//The format specifier inside the %(...%) is
//automatically applied to each element of a range
//Thus prints each line flanked by |
ob.writefln("|%(%2d %)|", row);
}
return ob.toString;
}
 
Matrix kronecker(Matrix m1, Matrix m2) {
Matrix p = new uint[][m1.length*m2.length];
foreach(r1i, r1; m1) {
foreach(r2i, r2; m2) {
auto rp = new uint[r1.length*r2.length];
foreach(c1i, e1; r1) {
foreach(c2i, e2; r2) {
rp[c1i*r2.length+c2i] = e1*e2;
}
}
p[r1i*m2.length+r2i] = rp;
}
}
return p;
}
 
void sample(Matrix m1, Matrix m2) {
auto res = kronecker(m1, m2);
writefln("Matrix A:\n%s\nMatrix B:\n%s\nA (X) B:\n%s", m1.toString, m2.toString, res.toString);
}
 
void main() {
Matrix A = [[1,2],[3,4]];
Matrix B = [[0,5],[6,7]];
sample(A,B);
Matrix C =
[[0,1,0],
[1,1,1],
[0,1,0]];
Matrix D =
[[1,1,1,1],
[1,0,0,1],
[1,1,1,1]];
sample(C,D);
}
</syntaxhighlight>
 
Output:
<pre>
Matrix A:
| 1 2|
| 3 4|
Matrix B:
| 0 5|
| 6 7|
A (X) B:
| 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|
A (X) B:
| 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|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}}
<syntaxhighlight lang="factor">USING: kernel math.matrices.extras prettyprint ;
 
{ { 1 2 } { 3 4 } }
{ { 0 5 } { 6 7 } }
{ { 0 1 0 } { 1 1 1 } { 0 1 0 } }
{ { 1 1 1 1 } { 1 0 0 1 } { 1 1 1 1 } }
[ kronecker-product . ] 2bi@</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|Fortran}}==
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. <syntaxhighlight lang="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.
Considers the arrays to be addressed as A(row,column), despite any storage order arrangements. .
Creating array AB to fit here, adjusting the caller's array AB, may not work on some compilers.
INTEGER A(:,:),B(:,:) !Two-dimensional arrays, lower bound one.
INTEGER, ALLOCATABLE:: AB(:,:) !To be created to fit.
INTEGER R,RA,RB,C,CA,CB,I !Assistants.
RA = UBOUND(A,DIM = 1) !Ascertain the upper bounds of the incoming arrays.
CA = UBOUND(A,DIM = 2) !Their lower bounds will be deemed one,
RB = UBOUND(B,DIM = 1) !And the upper bound as reported will correspond.
CB = UBOUND(B,DIM = 2) !UBOUND(A) would give an array of two values, RA and CA, more for higher dimensionality.
WRITE (6,1) "A",RA,CA,"B",RB,CB,"A.k.B",RA*RB,CA*CB !Announce.
1 FORMAT (3(A," is ",I0,"x",I0,1X)) !Three sets of sizes.
IF (ALLOCATED(AB)) DEALLOCATE(AB) !Discard any lingering storage.
ALLOCATE (AB(RA*RB,CA*CB)) !Obtain the exact desired size.
R = 0 !Syncopation: start the row offset.
DO I = 1,RA !Step down the rows of A.
C = 0 !For each row, start the column offset.
DO J = 1,CA !Step along the columns of A.
AB(R + 1:R + RB,C + 1:C + CB) = A(I,J)*B !Place a block of B values.
C = C + CB !Advance a block of columns.
END DO !On to the next column of A.
R = R + RB !Advance a block of rows.
END DO !On to the next row of A.
END SUBROUTINE KPRODUCT !No tests for bad parameters, or lack of storage...
 
SUBROUTINE SHOW(F,A) !Write array A in row,column order.
INTEGER F !Output file unit number.
INTEGER A(:,:) !The 2-D array, lower bound one.
INTEGER R !The row stepper.
DO R = 1,UBOUND(A,DIM = 1) !Each row gets its own line.
WRITE (F,1) A(R,:) !Write all the columns of that row.
1 FORMAT (666I3) !This suffices for the example.
END DO !On to the next row.
END SUBROUTINE SHOW !WRITE (F,*) A or similar would show A as if transposed.
END MODULE ARRAYMUSH !That was simple enough.
 
PROGRAM POKE
USE ARRAYMUSH
INTEGER A(2,2),B(2,2) !First test: square arrays.
INTEGER, ALLOCATABLE:: AB(:,:) !To be created for each result.
INTEGER C(3,3),D(3,4) !Second test: some rectilinearity.
DATA A/1,3, 2,4/,B/0,6, 5,7/ !Furrytran uses "column-major" order for successive storage elements.
DATA C/0,1,0, 1,1,1, 0,1,0/ !So, the first three values go down the rows of the first column.
DATA D/1,1,1, 1,0,1, 1,0,1, 1,1,1/!And then follow the values for the next column, etc.
 
WRITE (6,*) "First test..."
CALL KPRODUCT(A,B,AB)
CALL SHOW (6,AB)
 
WRITE (6,*)
WRITE (6,*) "Second test..."
CALL KPRODUCT(C,D,AB)
CALL SHOW (6,AB)
 
END</syntaxhighlight>
 
Output:
<pre>
First test...
A is 2x2 B is 2x2 A.k.B is 4x4
0 5 0 10
6 7 12 14
0 15 0 20
18 21 24 28
 
Second test...
A is 3x3 B is 3x4 A.k.B is 9x12
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>
 
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, <syntaxhighlight lang="fortran">AB(i,j) = A((i - 1)/RB + 1,(j - 1)/CB + 1)*B(MOD(i - 1,RB) + 1,MOD(j - 1,CB) + 1))</syntaxhighlight> 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 292 ⟶ 1,793:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>[ 0 5 0 10]
Line 308 ⟶ 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===
<syntaxhighlight lang="go">package main
 
import (
"fmt"
"strings"
)
 
type uintMatrix [][]uint
 
func (m uintMatrix) String() string {
var max uint
for _, r := range m {
for _, e := range r {
if e > max {
max = e
}
}
}
w := len(fmt.Sprint(max))
b := &strings.Builder{}
for _, r := range m {
fmt.Fprintf(b, "|%*d", w, r[0])
for _, e := range r[1:] {
fmt.Fprintf(b, " %*d", w, e)
}
fmt.Fprintln(b, "|")
}
return b.String()
}
 
func kronecker(m1, m2 uintMatrix) uintMatrix {
p := make(uintMatrix, len(m1)*len(m2))
for r1i, r1 := range m1 {
for r2i, r2 := range m2 {
rp := make([]uint, len(r1)*len(r2))
for c1i, e1 := range r1 {
for c2i, e2 := range r2 {
rp[c1i*len(r2)+c2i] = e1 * e2
}
}
p[r1i*len(m2)+r2i] = rp
}
}
return p
}
 
func sample(m1, m2 uintMatrix) {
fmt.Println("m1:")
fmt.Print(m1)
fmt.Println("m2:")
fmt.Print(m2)
fmt.Println("m1 ⊗ m2:")
fmt.Print(kronecker(m1, m2))
}
 
func main() {
sample(uintMatrix{
{1, 2},
{3, 4},
}, uintMatrix{
{0, 5},
{6, 7},
})
sample(uintMatrix{
{0, 1, 0},
{1, 1, 1},
{0, 1, 0},
}, uintMatrix{
{1, 1, 1, 1},
{1, 0, 0, 1},
{1, 1, 1, 1},
})
}</syntaxhighlight>
{{out}}
<pre>
m1:
|1 2|
|3 4|
m2:
|0 5|
|6 7|
m1 ⊗ m2:
| 0 5 0 10|
| 6 7 12 14|
| 0 15 0 20|
|18 21 24 28|
m1:
|0 1 0|
|1 1 1|
|0 1 0|
m2:
|1 1 1 1|
|1 0 0 1|
|1 1 1 1|
m1 ⊗ m2:
|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 go.matrix===
<syntaxhighlight 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},
})))
}</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>
===Library gonum/matrix===
Gonum/matrix doesn't have the Kronecker product, but here's an implementation using available methods.
<syntaxhighlight 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,
}))))
}</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|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 (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 343 ⟶ 2,160:
[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|J}}==
 
We can build Kronecker product from tensor outer product by transposing some dimensions of the result and then merging some dimensions.
 
Explicit implementation:
 
<syntaxhighlight lang="j">KP=: dyad def ',/"2 ,/ 1 3 |: x */ y'</syntaxhighlight>
 
Tacit:
 
<syntaxhighlight lang="j">KP=: 1 3 ,/"2@(,/)@|: */</syntaxhighlight>
 
these definitions are functionally equivalent.
 
Task examples:
 
<syntaxhighlight lang="j"> M=: 1+i.2 2
N=: (+4**)i.2 2
P=: -.0 2 6 8 e.~i.3 3
Q=: -.5 6 e.~i.3 4
M KP N
0 5 0 10
6 7 12 14
0 15 0 20
18 21 24 28
P KP Q
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</syntaxhighlight>
 
=={{header|Java}}==
 
<syntaxhighlight lang="java">
package kronecker;
 
/**
* Defines a function to calculate the Kronecker product of two
* rectangular matrices and tests it with two examples.
*/
public class Product {
/**
* Find the Kronecker product of the arguments.
* @param a The first matrix to multiply.
* @param b The second matrix to multiply.
* @return A new matrix: the Kronecker product of the arguments.
*/
public static int[][] product(final int[][] a, final int[][] b) {
// Create matrix c as the matrix to fill and return.
// The length of a matrix is its number of rows.
final int[][] c = new int[a.length*b.length][];
// Fill in the (empty) rows of c.
// The length of each row is the number of columns.
for (int ix = 0; ix < c.length; ix++) {
final int num_cols = a[0].length*b[0].length;
c[ix] = new int[num_cols];
}
// Now fill in the values: the products of each pair.
// Go through all the elements of a.
for (int ia = 0; ia < a.length; ia++) {
for (int ja = 0; ja < a[ia].length; ja++) {
// For each element of a, multiply it by all the elements of b.
for (int ib = 0; ib < b.length; ib++) {
for (int jb = 0; jb < b[ib].length; jb++) {
c[b.length*ia+ib][b[ib].length*ja+jb] = a[ia][ja] * b[ib][jb];
}
}
}
}
 
// Return the completed product matrix c.
return c;
}
 
/**
* Print an integer matrix, lining up the columns by the width
* of the longest printed element.
* @param m The matrix to print.
*/
public static void print_matrix(final int[][] m) {
// Printing the matrix neatly is the most complex part.
// For clean formatting, convert each number to a string
// and find length of the longest of these strings.
// Build a matrix of these strings to print later.
final String[][] sts = new String[m.length][];
int max_length = 0; // Safe, since all lengths are positive here.
for (int im = 0; im < m.length; im++) {
sts[im] = new String[m[im].length];
for (int jm = 0; jm < m[im].length; jm++) {
final String st = String.valueOf(m[im][jm]);
if (st.length() > max_length) {
max_length = st.length();
}
sts[im][jm] = st;
}
}
 
// Now max_length holds the length of the longest string.
// Build a format string to right justify the strings in a field
// of this length.
final String format = String.format("%%%ds", max_length);
for (int im = 0; im < m.length; im++) {
System.out.print("|");
// Stop one short to avoid a trailing space.
for (int jm = 0; jm < m[im].length - 1; jm++) {
System.out.format(format, m[im][jm]);
System.out.print(" ");
}
System.out.format(format, m[im][m[im].length - 1]);
System.out.println("|");
}
}
 
/**
* Run a test by printing the arguments, computing their
* Kronecker product, and printing it.
* @param a The first matrix to multiply.
* @param b The second matrix to multiply.
*/
private static void test(final int[][] a, final int[][] b) {
// Print out matrices and their product.
System.out.println("Testing Kronecker product");
System.out.println("Size of matrix a: " + a.length + " by " + a[0].length);
System.out.println("Matrix a:");
print_matrix(a);
System.out.println("Size of matrix b: " + b.length + " by " + b[0].length);
System.out.println("Matrix b:");
print_matrix(b);
System.out.println("Calculating matrix c as Kronecker product");
final int[][] c = product(a, b);
System.out.println("Size of matrix c: " + c.length + " by " + c[0].length);
System.out.println("Matrix c:");
print_matrix(c);
}
 
/**
* Create the matrices for the first test and run the test.
*/
private static void test1() {
// Test 1: Create a and b.
final int[][] a = new int[2][]; // 2 by 2
a[0] = new int[]{1, 2};
a[1] = new int[]{3, 4};
final int[][] b = new int[2][]; // 2 by 2
b[0] = new int[]{0, 5};
b[1] = new int[]{6, 7};
// Run the test.
test(a, b);
}
 
/**
* Create the matrices for the first test and run the test.
*/
private static void test2() {
// Test 2: Create a and b.
final int[][] a = new int[3][]; // 3 by 3
a[0] = new int[]{0, 1, 0};
a[1] = new int[]{1, 1, 1};
a[2] = new int[]{0, 1, 0};
final int[][] b = new int[3][]; // 3 by 4
b[0] = new int[]{1, 1, 1, 1};
b[1] = new int[]{1, 0, 0, 1};
b[2] = new int[]{1, 1, 1, 1};
// Run the test.
test(a, b);
}
 
/**
* Run the program to run the two tests.
* @param args Command line arguments (not used).
*/
public static void main(final String[] args) {
// Test the product method.
test1();
test2();
}
 
}
</syntaxhighlight>
 
{{Output}}
<pre>
Testing Kronecker product
Size of matrix a: 2 by 2
Matrix a:
|1 2|
|3 4|
Size of matrix b: 2 by 2
Matrix b:
|0 5|
|6 7|
Calculating matrix c as Kronecker product
Size of matrix c: 4 by 4
Matrix c:
| 0 5 0 10|
| 6 7 12 14|
| 0 15 0 20|
|18 21 24 28|
Testing Kronecker product
Size of matrix a: 3 by 3
Matrix a:
|0 1 0|
|1 1 1|
|0 1 0|
Size of matrix b: 3 by 4
Matrix b:
|1 1 1 1|
|1 0 0 1|
|1 1 1 1|
Calculating matrix c as Kronecker product
Size of matrix c: 9 by 12
Matrix c:
|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|JavaScript}}==
Line 348 ⟶ 2,393:
====Version #1.====
{{Works with|Chrome}}
<langsyntaxhighlight lang="javascript">
// matkronprod.js
// Prime function:
Line 366 ⟶ 2,411:
}
}
</langsyntaxhighlight>
 
;Required tests:
<langsyntaxhighlight lang="html">
<!-- KronProdTest.html -->
<html><head>
Line 388 ⟶ 2,433:
</head><body></body>
</html>
</langsyntaxhighlight>
{{Output}} '''Console and page results'''
<pre>
Line 428 ⟶ 2,473:
{{trans|PARI/GP}}
{{Works with|Chrome}}
<langsyntaxhighlight lang="javascript">
// matkronprod2.js
// Prime function:
Line 459 ⟶ 2,504:
}
}
</langsyntaxhighlight>
;Required tests:
<langsyntaxhighlight lang="html">
<!-- KronProdTest2.html -->
<html><head>
Line 480 ⟶ 2,525:
</head><body></body>
</html>
</langsyntaxhighlight>
 
{{Output}} '''Console and page results'''
Line 490 ⟶ 2,535:
====ES6====
{{Trans|Haskell}}
(As JavaScript is now widely embedded in non-browser contexts, a non-HTML string value is returned here, rather than invokingmaking acalls DOMto methodmethods 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';
 
// GENERIC FUNCTIONS --------------------------------------------- KRONECKER PRODUCT OF TWO MATRICES ---------
 
// kprod :: [[Num]] -> [[Num]] -> [[Num]]
const kprod = xs =>
ys => concatMap(
compose(map(concat), transpose)
)(
map(map(
flip(compose(map, map, mul))(ys)
))(xs)
);
 
// ----------------------- TEST ------------------------
// main :: IO ()
const main = () =>
unlines(map(compose(unlines, map(show)))([
kprod([
[1, 2],
[3, 4]
])([
[0, 5],
[6, 7]
]), [], // One empty output line
kprod([
[0, 1, 0],
[1, 1, 1],
[0, 1, 0]
])([
[1, 1, 1, 1],
[1, 0, 0, 1],
[1, 1, 1, 1]
])
]));
 
 
// ----------------- GENERIC FUNCTIONS -----------------
 
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
x => fs.reduceRight((a, f) => f(a), x);
 
 
// concat :: [[a]] -> [a]
const concat = xs => [].concat.apply([], xs);
 
 
// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = (f, xs) => [].concat.apply([], xs.map(f));
xs => xs.flatMap(f);
 
 
// flip :: (a -> b -> c) -> b -> a -> c
const flip = f =>
x => y => f(y)(x);
 
// 2 or more arguments
// curry :: Function -> Function
const curry = (f, ...args) => {
const go = xs => xs.length >= f.length ? (f.apply(null, xs)) :
function () {
return go(xs.concat([].slice.apply(arguments)));
};
return go([].slice.call(args, 1));
};
 
// map :: (a -> b) -> [a] -> [b]
const map = curry((f, xs) => xs.map(f));
xs => xs.map(f);
 
 
// mul (*) :: Num a => a -> a -> a
const mul = a =>
b => a * b;
 
 
// show :: a -> String
const show = x => JSON.stringify(x); //, null, 2);
JSON.stringify(x); //, null, 2);
 
 
// transpose :: [[a]] -> [[a]]
const transpose = xs =>
xs[0].map((_, col) => xs.map(row => row[col]));
 
 
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
xs.join('\n');
 
 
// MAIN ---
// KRONECKER PRODUCT OF TWO MATRICES --------------------------------------
console.log(main());
 
})();</syntaxhighlight>
// kprod :: [[Num]] -> [[Num]] -> [[Num]]
const kprod = (xs, ys) =>
concatMap(
m => map(concat, transpose(m)),
map(map(f(ys)), xs)
);
 
// (* n) mapped over each element in a matrix
// f :: [[Num]] -> Num -> [[Num]]
const f = curry((mx, n) => map(map(x => x * n), mx));
 
// TEST -------------------------------------------------------------------
return unlines(map(rows => unlines(map(show, rows)), [
kprod([
[1, 2],
[3, 4]
], [
[0, 5],
[6, 7]
]), [], // One empty output line
kprod([
[0, 1, 0],
[1, 1, 1],
[0, 1, 0]
], [
[1, 1, 1, 1],
[1, 0, 0, 1],
[1, 1, 1, 1]
])
]));
})();</lang>
{{Out}}
<pre>[0,5,0,10]
Line 574 ⟶ 2,638:
[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|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.
<syntaxhighlight lang="jq">def kprod(a; b):
 
# element-wise multiplication of a matrix by a number, "c"
def multiply(c): map( map(. * c) );
 
# "right" should be a vector with the same length as the input
def laminate(right):
[range(0; right|length) as $i
| (.[$i] + [right[$i]]) ];
 
# "matrix" and the input matrix should have the same number of rows
def addblock(matrix):
reduce (matrix|transpose)[] as $v (.; laminate($v));
 
(a[0]|length) as $m
| reduce range(0; a|length) as $i ([];
. + reduce range(0; $m) as $j ([];
addblock( b | multiply(a[$i][$j]) ) ));</syntaxhighlight>
 
Examples:
<syntaxhighlight lang="jq">
def left: [[ 1, 2], [3, 4]];
def right: [[ 0, 5], [6, 7]];
 
kprod(left;right)</syntaxhighlight>
{{out}}
<pre>[[0,5,0,10],[6,7,12,14],[0,15,0,20],[18,21,24,28]]</pre>
 
<syntaxhighlight 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)</syntaxhighlight>
{{out}}
<pre>[[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|Julia}}==
<syntaxhighlight lang="julia"># v0.6
 
# Julia has a builtin kronecker product function
a = [1 2; 3 4]
b = [0 5; 6 7]
k = kron(a, b)
println("$a × $b =")
for row in 1:size(k)[1]
println(k[row,:])
end
println()
 
a = [0 1 0; 1 1 1; 0 1 0]
b = [1 1 1 1; 1 0 0 1; 1 1 1 1]
k = kron(a, b)
println("$a × $b =")
for row in 1:size(k)[1]
println(k[row,:])
end</syntaxhighlight>
 
{{out}}
<pre>[1 2; 3 4] × [0 5; 6 7] =
[0, 5, 0, 10]
[6, 7, 12, 14]
[0, 15, 0, 20]
[18, 21, 24, 28]
 
[0 1 0; 1 1 1; 0 1 0] × [1 1 1 1; 1 0 0 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]
[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|Kotlin}}==
{{trans|JavaScript (Imperative #2)}}
<syntaxhighlight lang ="scala">// version 1.1.12 (JVM)
 
typealias Matrix = Array<IntArray>
Line 593 ⟶ 2,743:
for (k in 0 until p)
for (l in 0 until q)
r[p * i + k][q * j + l] = a[i][j] * b[k][l]
return r
}
Line 608 ⟶ 2,758:
printMatrix("Kronecker product:", r)
}
 
fun main(args: Array<String>) {
var a: Matrix
Line 633 ⟶ 2,783:
intArrayOf(1, 0, 0, 1),
intArrayOf(1, 1, 1, 1)
)
r = kroneckerProduct(a, b)
printAll(a, b, r)
}</langsyntaxhighlight>
 
{{out}}
Line 675 ⟶ 2,825:
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0]
</pre>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">
function prod( a, b )
print( "\nPRODUCT:" )
for m = 1, #a do
for p = 1, #b do
for n = 1, #a[m] do
for q = 1, #b[p] do
io.write( string.format( "%3d ", a[m][n] * b[p][q] ) )
end
end
print()
end
end
end
--[[entry point]]--
a = { { 1, 2 }, { 3, 4 } }; b = { { 0, 5 }, { 6, 7 } }
prod( 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 } }
prod( a, b )
</syntaxhighlight>
{{out}}
<pre>
PRODUCT:
0 5 0 10
6 7 12 14
0 15 0 20
18 21 24 28
 
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|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight 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</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|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>
 
=={{header|Nim}}==
Same as Kotlin but with a generic Matrix type.
 
<syntaxhighlight lang="nim">import strutils
 
type Matrix[M, N: static Positive; T: SomeNumber] = array[M, array[N, T]]
 
func kroneckerProduct[M, N, P, Q: static int; T: SomeNumber](
a: Matrix[M, N, T], b: Matrix[P, Q, T]): Matrix[M * P, N * Q, T] =
for i in 0..<M:
for j in 0..<N:
for k in 0..<P:
for l in 0..<Q:
result[i * P + k][j * Q + l] = a[i][j] * b[k][l]
 
proc `$`(m: Matrix): string =
for row in m:
result.add '['
let length = result.len
for val in row:
result.addSep(" ", length)
result.add ($val).align(2)
result.add "]\n"
 
 
when isMainModule:
 
const
A1: Matrix[2, 2, int] = [[1, 2], [3, 4]]
B1: Matrix[2, 2, int] = [[0, 5], [6, 7]]
 
echo "Matrix A:\n", A1
echo "Matrix B:\n", B1
echo "Kronecker product:\n", kroneckerProduct(A1, B1)
 
const
A2: Matrix[3, 3, int] = [[0, 1, 0], [1, 1, 1], [0, 1, 0]]
B2: Matrix[3, 4, int] = [[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]]
 
echo "Matrix A:\n", A2
echo "Matrix B:\n", B2
echo "Kronecker product:\n", 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|Octave}}==
<syntaxhighlight lang="octave">>> kron([1 2; 3 4], [0 5; 6 7])
ans =
 
0 5 0 10
6 7 12 14
0 15 0 20
18 21 24 28
 
>> kron([0 1 0; 1 1 1; 0 1 0], [1 1 1 1; 1 0 0 1; 1 1 1 1])
ans =
 
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</syntaxhighlight>
 
=={{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 706 ⟶ 3,268:
matprows("Sample 2 result:",r);
}
</langsyntaxhighlight>
{{Output}}
Line 726 ⟶ 3,288:
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0]
</pre>
=== Version #2 ===
=={{header|Perl 6}}==
This version is from B. Allombert. 12/12/17
{{Works with|PARI/GP|2.9.1 and above}}
<syntaxhighlight lang="parigp">
\\ Print title and matrix mat rows. aev
matprows(title,mat)={print(title); for(i=1,#mat[,1], print(mat[i,]))}
\\
\\ Create and return the Kronecker product of the a and b matrices. 12/12/17 ba
kronprod(a,b)={return(matconcat(matrix(#a[,1],#a,i,j,a[i,j]*b)))}
{\\ Requireq tests:
my(a,b,r);
\\ Sample 1
a=[1,2;3,4];
b=[0,5;6,7];
r=kronprod(a,b);
matprows("Sample 1 result:",r);
\\ Sample 2
a=[0,1,0;1,1,1;0,1,0];
b=[1,1,1,1;1,0,0,1;1,1,1,1];
r=kronprod(a,b);
matprows("Sample 2 result:",r);
}
</syntaxhighlight>
{{Output}}
<pre>
Sample 1 result:
[0, 5, 0, 10]
[6, 7, 12, 14]
[0, 15, 0, 20]
[18, 21, 24, 28]
Sample 2 result:
[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|Perl}}==
<syntaxhighlight lang="perl">#!/usr/bin/perl
use strict;
use warnings;
use PDL;
 
sub kron {
my ($x, $y) = @_;
 
return $x->dummy(0)
->dummy(0)
->mult($y, 0)
->clump(0, 2)
->clump(1, 2)
}
 
my @mats = (
[pdl([[1, 2], [3, 4]]),
pdl([[0, 5], [6, 7]])],
[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";
}</syntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="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>
<span style="color: #000000;">ac</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><span style="color: #000000;">1</span><span style="color: #0000FF;">]),</span>
<span style="color: #000000;">br</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">bc</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ac</span><span style="color: #0000FF;">*</span><span style="color: #000000;">bc</span><span style="color: #0000FF;">),</span><span style="color: #000000;">ar</span><span style="color: #0000FF;">*</span><span style="color: #000000;">br</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">ia</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">ar</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">i0</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">ia</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">br</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">ja</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">ac</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">j0</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">ja</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">bc</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">ib</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">br</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i0</span><span style="color: #0000FF;">+</span><span style="color: #000000;">ib</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">jb</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">bc</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">j</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">j0</span><span style="color: #0000FF;">+</span><span style="color: #000000;">jb</span>
<span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ia</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ja</span><span style="color: #0000FF;">]*</span><span style="color: #000000;">b</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ib</span><span style="color: #0000FF;">,</span><span style="color: #000000;">jb</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">}},</span>
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">}},</span>
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}},</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</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;">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>
<!--</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|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}}==
<syntaxhighlight lang="purebasic">EnableExplicit
DataSection
Matrix_A_B_Dimension_Bsp1:
Data.i 2,2,?MatrixA_Werte_Bsp1,2,2,?MatrixB_Werte_Bsp1
Matrix_A_B_Dimension_Bsp2:
Data.i 3,3,?MatrixA_Werte_Bsp2,3,4,?MatrixB_Werte_Bsp2
MatrixA_Werte_Bsp1:
Data.i 1,2,3,4
MatrixA_Werte_Bsp2:
Data.i 0,1,0,1,1,1,0,1,0
MatrixB_Werte_Bsp1:
Data.i 0,5,6,7
MatrixB_Werte_Bsp2:
Data.i 1,1,1,1,1,0,0,1,1,1,1,1
EndDataSection
 
Define.i ma, na, mb, nb, adr1, adr2, i, j, k, l
Define mk$
 
Gosub Bsp1_Matrix_A_B : Gosub LoadMatrix : Gosub Bsp2_Matrix_A_B : Gosub LoadMatrix : End
 
LoadMatrix:
Read.i ma
Read.i na
Read.i adr1
Read.i mb
Read.i nb
Read.i adr2
 
Dim mxa.i(ma,na)
Dim mxb.i(mb,nb)
NewMap mxc.i()
 
For i=1 To ma
For j=1 To na
mxa(i,j)=PeekI(adr1)
adr1+SizeOf(Integer)
Next
Next
 
For i=1 To mb
For j=1 To nb
mxb(i,j)=PeekI(adr2)
adr2+SizeOf(Integer)
Next
Next
 
OpenConsole("Kronecker product")
PrintN("Matrix A:")
For i=1 To ma ; Zeile
Print("|")
For j=1 To na ; Spalte
Print(RSet(Str(mxa(i,j)),2," ")+" ")
Next
PrintN("|")
Next
PrintN("")
 
PrintN("Matrix B:")
For i=1 To mb ; Zeile
Print("|")
For j=1 To nb ; Spalte
Print(RSet(Str(mxb(i,j)),2," ")+" ")
Next
PrintN("|")
Next
PrintN("")
 
PrintN("Matrix C=AxB")
For i=1 To ma ; Zeile MA
For j=1 To na ; Spalte MA
For k=1 To mb ; Zeile MB
For l=1 To nb ; Spalte MB
mxc(Str(i)+","+Str(j)+","+Str(k)+","+Str(l))=mxa(i,j)*mxb(k,l)
Next
Next
Next
Next
 
For i=1 To ma ; Zeile MA
For k=1 To mb; Zeile MB
Print("|")
For j=1 To na ; Spalte MA
For l=1 To nb ; Spalte MB
mk$=Str(i)+","+Str(j)+","+Str(k)+","+Str(l)
If FindMapElement(mxc(),mk$)
Print(RSet(Str(mxc()),2," ")+" ")
EndIf
Next
Next
PrintN("|")
Next
Next
PrintN("Press return") : Input()
Return
 
Bsp1_Matrix_A_B:
Restore Matrix_A_B_Dimension_Bsp1
Return
 
Bsp2_Matrix_A_B:
Restore Matrix_A_B_Dimension_Bsp2
Return</syntaxhighlight>
{{out}}
<pre>Matrix A:
| 1 2 |
| 3 4 |
 
Matrix B:
| 0 5 |
| 6 7 |
 
Matrix C=AxB
| 0 5 0 10 |
| 6 7 12 14 |
| 0 15 0 20 |
|18 21 24 28 |
Press return
 
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 C=AxB
| 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 |
Press return</pre>
 
=={{header|Python}}==
===Version 1===
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.
 
<syntaxhighlight lang="python">#!/usr/bin/env python3
 
# Sample 1
a1 = [[1, 2], [3, 4]]
b1 = [[0, 5], [6, 7]]
 
# Sample 2
a2 = [[0, 1, 0], [1, 1, 1], [0, 1, 0]]
b2 = [[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]]
 
def kronecker(matrix1, matrix2):
final_list = []
sub_list = []
 
count = len(matrix2)
 
for elem1 in matrix1:
counter = 0
check = 0
while check < count:
for num1 in elem1:
for num2 in matrix2[counter]:
sub_list.append(num1 * num2)
counter += 1
final_list.append(sub_list)
sub_list = []
check +=1
return final_list
 
# Result 1
result1 = kronecker(a1, b1)
for elem in result1:
print(elem)
 
print("")
 
# Result 2
result2 = kronecker(a2, b2)
for elem in result2:
print(elem)</syntaxhighlight>
 
Result:
<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>
===Version 2===
This version was initially based on and uses a similar looping structure to version 1, but it is much less readable for those not familiar with Python list comprehensions. Nevertheless I think it serves as a wonderful example of what list comprehensions can be good for. My original version of this code took an iterable as input and recursively computed the Kronecker product of any number of matrices, which is a very common use case in arenas where the Kronecker product is used. I have reduced this example to match the task description, but I encourage learners to attempt to reimplement it.
 
Code:
<syntaxhighlight lang="python"># Sample 1
r = [[1, 2], [3, 4]]
s = [[0, 5], [6, 7]]
 
# Sample 2
t = [[0, 1, 0], [1, 1, 1], [0, 1, 0]]
u = [[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]]
 
def kronecker(matrix1, matrix2):
return [[num1 * num2 for num1 in elem1 for num2 in matrix2[row]] for elem1 in matrix1 for row in range(len(matrix2))]
 
# Result 1:
for row in kronecker(r, s):
print(row)
print()
 
# Result 2
for row in kronecker(t, u):
print(row)</syntaxhighlight>
 
===Version 3===
We can still get the power of list comprehensions (without generating the unreadably long single lines of code referred to above) by de-sugaring them down to the underlying list monad pattern.
 
Version three rewrites the list comprehension above in terms of '''concatMap''' (the 'bind' or 'insert' operator for list monads), to which we pass a function that returns its value wrapped in a list. (Where values are filtered out by a condition, we return an empty list).
 
Note, for example, that the innermost expression here has to be <code>lambda num1: [num1 * num2]</code>, rather than just <code>lambda num1: num1 * num2</code>.
 
The outermost part of the '''concatMap''' nest corresponds to the rightmost part of the list comprehension expression.
 
(Versions 2 and 3 produce the same output from the same test)
<syntaxhighlight lang="python">from itertools import (chain)
 
 
# kronecker :: [[a]] -> [[a]] -> [[a]]
def kronecker(m1, m2):
return concatMap(
lambda row2: concatMap(
lambda elem2: [concatMap(
lambda num2: concatMap(
lambda num1: [num1 * num2],
elem2
),
m1[row2]
)],
m2
),
range(len(m2))
)
 
 
# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f, xs):
return list(
chain.from_iterable(
map(f, xs)
)
)
 
 
if __name__ == '__main__':
# Sample 1
r = [[1, 2], [3, 4]]
s = [[0, 5], [6, 7]]
 
# Sample 2
t = [[0, 1, 0], [1, 1, 1], [0, 1, 0]]
u = [[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]]
 
# Result 1:
for row in kronecker(r, s):
print(row)
print()
 
# Result 2
for row in kronecker(t, u):
print(row)</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|R}}==
R has built-in Kronecker product operator for a and b matrices: '''a %x% b'''.
<syntaxhighlight 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>
{{Output}}
<pre>
[,1] [,2] [,3] [,4]
[1,] 0 1 0 1
[2,] 1 0 1 0
[3,] 0 1 0 1
[4,] 1 0 1 0
 
Note: This resultant matrix could be used as initial for Checkerboard fractal.
</pre>
 
=={{header|Racket}}==
 
Uses typed racket, since the 'math/...' libraries are much more performant in that language.
 
<syntaxhighlight lang="racket">#lang typed/racket/base
 
(require math/array
math/matrix
racket/match)
 
(define-type (M A) (Matrix A))
 
(define #:forall (A B C) (general-⊗ [m1 : (M A)] [m2 : (M B)] [× : (A B -> C)]) : (M C)
(match-let* ((`(#(,rs1 ,cs1) . #(,rs2 ,cs2)) (cons (array-shape m1) (array-shape m2)))
(rs (* rs1 rs2))
(cs (* cs1 cs2)))
(for*/matrix: rs cs ((r (in-range rs)) (c (in-range cs))) : C
(let-values (((rq rr) (quotient/remainder r rs2))
((cq cr) (quotient/remainder c cs2)))
(× (array-ref m1 (vector rq cq)) (array-ref m2 (vector rr cr)))))))
 
;; Narrow to Number
(define (Kronecker-product [m1 : (M Number)] [m2 : (M Number)]) (general-⊗ m1 m2 *))
 
;; ---------------------------------------------------------------------------------------------------
(module+ test
(Kronecker-product (matrix [[1 2]
[3 4]])
(matrix [[0 5]
[6 7]]))
(Kronecker-product (matrix [[0 1 0]
[1 1 1]
[0 1 0]])
(matrix [[1 1 1 1]
[1 0 0 1]
[1 1 1 1]])))</syntaxhighlight>
 
{{out}}
<pre>(mutable-array #[#[0 5 0 10] #[6 7 12 14] #[0 15 0 20] #[18 21 24 28]])
(mutable-array
#[#[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|Raku}}==
(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 737 ⟶ 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 754 ⟶ 3,892:
(0 0 0 0 1 1 1 1 0 0 0 0)</pre>
 
=={{header|REXXlREXX}}==
A little extra coding was added to make the matrix glyphs and elementelements alignment look nicer.
<langsyntaxhighlight lang="rexx">/*REXX program calculates the Kronecker product of two matrices. two arbitrary size matrices. */
w=0; KP= 'Kronecker product' /*W≡max W: max width of matricany matrix elements.element*/
aMatamat= 2x2 1 2 3 4; bMat= 2x2 0 5/* define A matrix size and 6elements 7*/
bmat=2x2 0 5 6 7 /* " B " " " " */
call makeMat 'A', aMat; call makeMat 'B', bMat
Call makeMat 'A',amat /* construct A matrix from elements */
call KronMat KP
w=0;Call makeMat 'B',bmat /* " B say;" " say copies('░', 50); " say*/
Call KronMat 'Kronecker product' /* calculate the Kronecker product */
aMat= 3x3 0 1 0 1 1 1 0 1 0; bMat= 3x4 1 1 1 1 1 0 0 1 1 1 1 1
Call showMat what,arows*brows||'X'||arows*bcols
call makeMat 'A', aMat; call makeMat 'B', bMat
Say ''
call KronMat KP
Say copies('|',55)
exit /*stick a fork in it, we're all done. */
Say ''
/*──────────────────────────────────────────────────────────────────────────────────────*/
w=0 /* W: max width of any matrix element*/
KronMat: parse arg what; #=0; parse var @.a.shape aRows aCols
amat=3x3 0 1 0 1 1 1 0 1 0 /* define A matrix size and elements */
parse var @.b.shape bRows bCols
bmat=3x4 1 1 1 1 1 0 0 1 1 1 1 1 /* " do B " " " " rA=1 for aRows*/
Call makeMat 'A',amat /* construct A matrix from elements */
do rB=1 for bRows; #=#+1; ##=0; _=
Call makeMat 'B',bmat /* " do cA=1 forB aCols; x=@.a.rA.cA " " " */
Call KronMat 'Kronecker product' /* calculate the Kronecker product */
do cB=1 for bCols; y=@.b.rB.cB; ##=##+1; xy=x*y; _=_ xy
Call showMat what,arows*brows||'X'||arows*bcols
@.what.#.##=xy; w=max(w, length(xy) )
Exit end /*cB stick a fork in it, we're all done*/
/*--------------------------------------------------------------------*/
end /*cA*/
makemat:
end /*rB*/
Parse Arg what,size elements /*elements: e.1.1 e.1.2 - e.rows cols*/
end /*rA*/
Parse Var size rows 'X' cols
call showMat what, aRows*bRows || 'X' || aRows*bCols; return
x.what.shape=rows cols
/*──────────────────────────────────────────────────────────────────────────────────────*/
n=0
makeMat: parse arg what, size elements; arg , row 'X' col .; @.what.shape= row col
Do r=1 To rows
#=0; do r=1 for row /* [↓] bump item#; get item; max width*/
Do c=1 To cols
do c=1 for col; #=#+1; _=word(elements, #); w=max(w, length(_) )
@.what.r.cn=_n+1
element=word(elements,n)
end /*c*/ /* [↑] define an element of WHAT matrix*/
w=max(w,length(element))
end /*r*/
call showMat x.what, size; return.r.c=element
End
/*──────────────────────────────────────────────────────────────────────────────────────*/
End
showMat: parse arg what, size .; z='┌'; parse var size row 'X' col; $=left('', 6)
Call showMat what,size
say; say copies('═',7) 'matrix' what copies('═',7)
Return
do r=1 for row; _= '│'
/*--------------------------------------------------------------------*/
do c=1 for col; _=_ right(@.what.r.c, w); if r==1 then z=z left('',w)
kronmat: end /*c compute the Kronecker Product */
Parse Arg what
if r==1 then do; z=z '┐'; say $ z; end /*show the top part of matrix.*/
Parse Var x.a.shape arows acols
say $ _ '│'
Parse Var x.b.shape brows bcols
end /*r*/
rp=0 say $ translate(z, '└┘', "┌┐"); return /*show therow of product bot part of matrix.*/</lang>
Do ra=1 To arows
{{out|output|text=&nbsp; when using the default input:}}
Do rb=1 To brows
rp=rp+1 /* row of product */
cp=0 /* column of product */
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 -------
═══════ matrix A ═══════
+-----+
| 1 2 |
| 3 4 |
+-----+
 
------- matrix B -------
═══════ 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 -------
═══════ matrix A ═══════
+-------+
| 0 1 0 |
| 1 1 1 |
| 0 1 0 |
+-------+
 
------- matrix B -------
═══════ 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|Ring}}==
<syntaxhighlight lang="ring">
# Project : Kronecker product
 
a = [[1, 2], [3, 4]]
b = [[0, 5], [6, 7]]
la1 = 1
ua1 = 2
la2 = 1
ua2 = 2
lb1 = 1
ub1 = 2
lb2 = 1
ub2 = 2
kroneckerproduct(a,b)
see nl
 
la1 = 1
ua1 = 3
la2 = 1
ua2 = 3
lb1 = 1
ub1 = 3
lb2 = 1
ub2 = 3
x = [[0, 1, 0], [1, 1, 1], [0, 1, 0]]
y = [[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]]
kroneckerproduct(x, y)
 
func kroneckerproduct(a,b)
 
for i = la1 to ua1
for k = lb1 to ub1
see "["
for j = la2 to ua2
for l = lb2 to ub2
see a[i][j] * b[k][l]
if j = ua1 and l = ub2
see "]" + nl
else
see " "
ok
next
next
next
next
</syntaxhighlight>
Output:
<pre>
[0 5 0 10]
[6 7 12 14]
[0 15 0 20]
[18 21 24 28]
 
[0 0 0 1 1 1 0 0 0]
[0 0 0 1 0 0 0 0 0]
[0 0 0 1 1 1 0 0 0]
[1 1 1 1 1 1 1 1 1]
[1 0 0 1 0 0 1 0 0]
[1 1 1 1 1 1 1 1 1]
[0 0 0 1 1 1 0 0 0]
[0 0 0 1 0 0 0 0 0]
[0 0 0 1 1 1 0 0 0]
</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}}==
<syntaxhighlight lang="rust">fn main() {
 
let mut a = vec![vec![1., 2.], vec![3., 4.]];
let mut b = vec![vec![0., 5.], vec![6., 7.]];
 
let mut a_ref = &mut a;
let a_rref = &mut a_ref;
 
let mut b_ref = &mut b;
let b_rref = &mut b_ref;
 
let ab = kronecker_product(a_rref, b_rref);
 
println!("Kronecker product of\n");
for i in a {
println!("{:?}", i);
}
println!("\nand\n");
for i in b {
println!("{:?}", i);
}
println!("\nis\n");
for i in ab {
println!("{:?}", i);
}
 
println!("\n\n");
 
let mut a = vec![vec![0., 1., 0.],
vec![1., 1., 1.],
vec![0., 1., 0.]];
let mut b = vec![vec![1., 1., 1., 1.],
vec![1., 0., 0., 1.],
vec![1., 1., 1., 1.]];
 
let mut a_ref = &mut a;
let a_rref = &mut a_ref;
 
let mut b_ref = &mut b;
let b_rref = &mut b_ref;
 
let ab = kronecker_product(a_rref, b_rref);
 
println!("Kronecker product of\n");
for i in a {
println!("{:?}", i);
}
println!("\nand\n");
for i in b {
println!("{:?}", i);
}
println!("\nis\n");
for i in ab {
println!("{:?}", i);
}
 
println!("\n\n");
 
}
 
fn kronecker_product(a: &mut Vec<Vec<f64>>, b: &mut Vec<Vec<f64>>) -> Vec<Vec<f64>> {
let m = a.len();
let n = a[0].len();
let p = b.len();
let q = b[0].len();
let rtn = m * p;
let ctn = n * q;
 
let mut r = zero_matrix(rtn, ctn);
 
for i in 0..m {
for j in 0..n {
for k in 0..p {
for l in 0..q {
r[p * i + k][q * j + l] = a[i][j] * b[k][l];
}
}
}
}
r
}
 
fn zero_matrix(rows: usize, cols: usize) -> Vec<Vec<f64>> {
let mut matrix = Vec::with_capacity(cols);
for _ in 0..rows {
let mut col: Vec<f64> = Vec::with_capacity(rows);
for _ in 0..cols {
col.push(0.0);
}
matrix.push(col);
}
matrix
}
</syntaxhighlight>
{{out}}
<pre>
Kronecker product of
 
[1.0, 2.0]
[3.0, 4.0]
 
and
 
[0.0, 5.0]
[6.0, 7.0]
 
is
 
[0.0, 5.0, 0.0, 10.0]
[6.0, 7.0, 12.0, 14.0]
[0.0, 15.0, 0.0, 20.0]
[18.0, 21.0, 24.0, 28.0]
 
 
 
Kronecker product of
 
[0.0, 1.0, 0.0]
[1.0, 1.0, 1.0]
[0.0, 1.0, 0.0]
 
and
 
[1.0, 1.0, 1.0, 1.0]
[1.0, 0.0, 0.0, 1.0]
[1.0, 1.0, 1.0, 1.0]
 
is
 
[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
[1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0]
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]
 
 
 
</pre>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala"> object KroneckerProduct
{
/**Get the dimensions of the input matrix*/
def getDimensions(matrix : Array[Array[Int]]) : (Int,Int) = {
val dimensions = matrix.map(x => x.size)
(dimensions.size, dimensions(0))
}
 
/**Compute the Kronecker product between 2 input matrixes and return the result as a matrix*/
def kroneckerProduct(matrix1 : Array[Array[Int]], matrix2 : Array[Array[Int]]) : Array[Array[Int]] = {
val (r1,c1) = getDimensions(matrix1)
val (r2,c2) = getDimensions(matrix2)
 
val res = Array.ofDim[Int](r1*r2, c1*c2)
 
for(
i <- 0 until r1;
j <- 0 until c1;
k <- 0 until r2;
l <- 0 until c2
){
res(r2 * i + k)(c2 * j + l) = matrix1(i)(j) * matrix2(k)(l)
}
 
res
}
 
def main(args: Array[String]): Unit = {
val m1 = Array(Array(1, 2), Array(3, 4))
val m2 = Array(Array(0, 5), Array(6, 7))
println(kroneckerProduct(m1,m2).map(_.mkString("|")).mkString("\n"))
 
println("----------")
 
val m3 = Array(Array(0, 1, 0), Array(1, 1, 1), Array(0, 1, 0))
val m4 = Array(Array(1, 1, 1, 1), Array(1, 0, 0, 1), Array(1, 1, 1, 1))
println(kroneckerProduct(m3,m4).map(_.mkString("|")).mkString("\n"))
}
 
}
 
</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|Sidef}}==
{{trans|Raku}}
<syntaxhighlight lang="ruby">func kronecker_product(a, b) {
a ~X b -> map { _[0] ~X* _[1] }
}
 
kronecker_product([[1, 2], [3, 4]],
[[0, 5], [6, 7]]).each { .say }
 
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 }</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|Simula}}==
<syntaxhighlight lang="simula">BEGIN
 
PROCEDURE OUTMATRIX(A, W); INTEGER ARRAY A; INTEGER W;
BEGIN
INTEGER I, J;
INTEGER LA1, UA1;
INTEGER LA2, UA2;
 
LA1 := LOWERBOUND(A, 1); UA1 := UPPERBOUND(A, 1);
LA2 := LOWERBOUND(A, 2); UA2 := UPPERBOUND(A, 2);
 
FOR I := LA1 STEP 1 UNTIL UA1 DO
BEGIN
OUTTEXT("[");
FOR J := LA2 STEP 1 UNTIL UA2 DO
BEGIN
IF NOT (J = LA2) THEN OUTCHAR(' ');
OUTINT(A(I, J), W)
END;
OUTTEXT("]");
OUTIMAGE
END
END OUTMATRIX;
 
PROCEDURE KRONECKERPRODUCT(A, B, C); INTEGER ARRAY A, B, C;
BEGIN
INTEGER I, J, K, L, CI, CJ;
INTEGER LA1, UA1;
INTEGER LA2, UA2;
INTEGER LB1, UB1;
INTEGER LB2, UB2;
 
LA1 := LOWERBOUND(A, 1); UA1 := UPPERBOUND(A, 1);
LA2 := LOWERBOUND(A, 2); UA2 := UPPERBOUND(A, 2);
LB1 := LOWERBOUND(B, 1); UB1 := UPPERBOUND(B, 1);
LB2 := LOWERBOUND(B, 2); UB2 := UPPERBOUND(B, 2);
 
CI := 1;
FOR I := LA1 STEP 1 UNTIL UA1 DO
FOR K := LB1 STEP 1 UNTIL UB1 DO
BEGIN
CJ := 1;
FOR J := LA2 STEP 1 UNTIL UA2 DO
FOR L := LB2 STEP 1 UNTIL UB2 DO
BEGIN
C(CI, CJ) := A(I, J) * B(K, L);
CJ := CJ + 1
END;
CI := CI + 1
END
END KRONECKERPRODUCT;
! --- EXAMPLE 1 --- ;
BEGIN
INTEGER ARRAY A(1:2, 1:2);
INTEGER ARRAY B(1:2, 1:2);
INTEGER ARRAY C(1:4, 1:4);
 
! {{1, 2}, {3, 4}} ;
 
A(1, 1) := 1;
A(1, 2) := 2;
 
A(2, 1) := 3;
A(2, 2) := 4;
 
! {{0, 5}, {6, 7}} ;
 
B(1, 1) := 0;
B(1, 2) := 5;
 
B(2, 1) := 6;
B(2, 2) := 7;
 
OUTMATRIX(A, 2); OUTTEXT(" *"); OUTIMAGE;
OUTMATRIX(B, 2); OUTTEXT(" ="); OUTIMAGE;
 
KRONECKERPRODUCT(A, B, C);
 
OUTMATRIX(C, 2); OUTIMAGE
 
! OUTPUT:
 
! [ 0 5 0 10]
! [ 6 7 12 14]
! [ 0 15 0 20]
! [18 21 24 28] ;
 
END EXAMPLE 1;
 
! --- EXAMPLE 2 --- ;
BEGIN
INTEGER ARRAY X(1:3, 1:3);
INTEGER ARRAY Y(1:3, 1:4);
INTEGER ARRAY C(1:9, 1:12);
 
! {{0, 1, 0}, {1, 1, 1}, {0, 1, 0}} ;
 
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;
 
! {{1, 1, 1, 1}, {1, 0, 0, 1}, {1, 1, 1, 1}} ;
 
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;
 
OUTIMAGE;
 
OUTMATRIX(X, 1); OUTTEXT(" *"); OUTIMAGE;
OUTMATRIX(Y, 1); OUTTEXT(" ="); OUTIMAGE;
 
KRONECKERPRODUCT(X, Y, C);
 
OUTMATRIX(C, 1); OUTIMAGE;
! OUTPUT:
 
! [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] ;
 
END EXAMPLE 2;
END</syntaxhighlight>
{{out}}
<pre>
[ 1 2]
[ 3 4]
*
[ 0 5]
[ 6 7]
=
[ 0 5 0 10]
[ 6 7 12 14]
[ 0 15 0 20]
[18 21 24 28]
 
 
[0 1 0]
[1 1 1]
[0 1 0]
*
[1 1 1 1]
[1 0 0 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]
[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|Stata}}==
In Mata, the Kronecker product is the operator '''#'''.
 
<syntaxhighlight lang="stata">. mata
------------------------------------------------- mata (type end to exit) ----------
: a=1,2\3,4
 
: b=0,5\6,7
 
: a#b
1 2 3 4
+---------------------+
1 | 0 5 0 10 |
2 | 6 7 12 14 |
3 | 0 15 0 20 |
4 | 18 21 24 28 |
+---------------------+
 
: a=0,1,0\1,1,1\0,1,0
 
: b=1,1,1,1\1,0,0,1\1,1,1,1
 
: a#b
1 2 3 4 5 6 7 8 9 10 11 12
+-------------------------------------------------------------+
1 | 0 0 0 0 1 1 1 1 0 0 0 0 |
2 | 0 0 0 0 1 0 0 1 0 0 0 0 |
3 | 0 0 0 0 1 1 1 1 0 0 0 0 |
4 | 1 1 1 1 1 1 1 1 1 1 1 1 |
5 | 1 0 0 1 1 0 0 1 1 0 0 1 |
6 | 1 1 1 1 1 1 1 1 1 1 1 1 |
7 | 0 0 0 0 1 1 1 1 0 0 0 0 |
8 | 0 0 0 0 1 0 0 1 0 0 0 0 |
9 | 0 0 0 0 1 1 1 1 0 0 0 0 |
+-------------------------------------------------------------+
: end</syntaxhighlight>
 
=={{header|SuperCollider}}==
<syntaxhighlight lang="supercollider">// the iterative version is derived from the javascript one here:
(
f = { |a, b|
var m = a.size;
var n = a[0].size;
var p = b.size;
var q = b[0].size;
var rtn = m * p;
var ctn = n * q;
var res = { 0.dup(ctn) }.dup(rtn);
m.do { |i|
n.do { |j|
p.do { |k|
q.do { |l|
res[p*i+k][q*j+l] = a[i][j] * b[k][l];
}
}
}
};
res
};
)
 
// Like APL/J, SuperCollider has applicative operators, so here is a shorter version.
// the idea is to first replace every element of b with its product with all of a
// and then reshape the matrix appropriately
// note that +++ is lamination: [[1, 2, 3], [4, 5, 6]] +++ [100, 200] returns [ [ 1, 2, 3, 100 ], [ 4, 5, 6, 200 ] ].
 
(
f = { |a, b|
a.collect { |x|
x.collect { |y| b * y }.reduce('+++')
}.reduce('++')
}
)
 
// or shorter:
(a *.2 b).collect(_.reduce('+++')).reduce('++')
 
</syntaxhighlight>
 
<syntaxhighlight lang="supercollider">// to apply either of the two functions:
(
x = f.(
[
[0, 1, 0],
[1, 1, 1],
[0, 1, 0]
],
[
[1, 1, 1, 1],
[1, 0, 0, 1],
[1, 1, 1, 1]
]
)
)
</syntaxhighlight>
 
Results in:
 
<pre>
[
[ 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>
 
And:
 
<syntaxhighlight lang="supercollider">(
x = f.(
[
[ 1, 2 ],
[ 3, 4 ]
],
[
[ 0, 5 ],
[ 6, 7 ]
]
)
)
</syntaxhighlight>
 
returns:
<pre>
[
[ 0, 5, 0, 10 ],
[ 6, 7, 12, 14 ],
[ 0, 15, 0, 20 ],
[ 18, 21, 24, 28 ]
]
</pre>
 
=={{header|Swift}}==
 
<syntaxhighlight lang="swift">func kronecker(m1: [[Int]], m2: [[Int]]) -> [[Int]] {
let m = m1.count
let n = m1[0].count
let p = m2.count
let q = m2[0].count
let rtn = m * p
let ctn = n * q
 
var res = Array(repeating: Array(repeating: 0, count: ctn), count: rtn)
 
for i in 0..<m {
for j in 0..<n {
for k in 0..<p {
for l in 0..<q {
res[p * i + k][q * j + l] = m1[i][j] * m2[k][l]
}
}
}
}
 
return res
}
 
func printMatrix<T>(_ matrix: [[T]]) {
guard !matrix.isEmpty else {
print()
 
return
}
 
let rows = matrix.count
let cols = matrix[0].count
 
for i in 0..<rows {
for j in 0..<cols {
print(matrix[i][j], terminator: " ")
}
 
print()
}
}
 
 
func printProducts(a: [[Int]], b: [[Int]]) {
print("Matrix A:")
printMatrix(a)
print("Matrix B:")
printMatrix(b)
print("kronecker a b:")
printMatrix(kronecker(m1: a, m2: b))
print()
}
 
let a = [
[1, 2],
[3, 4]
]
 
let b = [
[0, 5],
[6, 7]
]
 
printProducts(a: a, b: b)
 
let a2 = [
[0, 1, 0],
[1, 1, 1],
[0, 1, 0]
]
 
let b2 = [
[1, 1, 1, 1],
[1, 0, 0, 1],
[1, 1, 1, 1]
]
 
printProducts(a: a2, b: b2)</syntaxhighlight>
 
{{out}}
 
<pre>Matrix A:
1 2
3 4
Matrix B:
0 5
6 7
kronecker a b:
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 a b:
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|Tcl}}==
<syntaxhighlight lang="tcl"># some helpers for matrices in nice string form:
proc parse_matrix {s} {
split [string trim $s] \n
}
 
proc print_matrix {m} {
foreach row $m {
puts [join [lmap x $row {format %3s $x}]]
}
}
 
# obvious imperative version using [foreach]
proc kroenecker {A B} {
foreach arow $A {
foreach brow $B {
set row {}
foreach a $arow {
foreach b $brow {
lappend row [expr {$a * $b}]
}
}
lappend result $row
}
}
return $result
}
 
proc lolcat {args} { ;# see https://wiki.tcl.tk/41507
concat {*}[uplevel 1 lmap $args]
}
 
# more compact but obtuse, using [lmap] and [lolcat]
proc kroenecker {A B} {
lolcat arow $A {
lmap brow $B {
lolcat a $arow {
lmap b $brow {
expr {$a * $b}
}
}
}
}
}
 
# demo:
set inputs {
{1 2
3 4}
{0 5
6 7}
 
{0 1 0
1 1 1
0 1 0}
{1 1 1 1
1 0 0 1
1 1 1 1}
}
 
foreach {a b} $inputs {
set a [parse_matrix $a]
set b [parse_matrix $b]
print_matrix [kroenecker $a $b]
puts ""
}</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|VBScript}}==
<syntaxhighlight lang="vb">' Kronecker product - 05/04/2017 ' array boundary iteration corrections 06/13/2023
dim a(),b(),r()
sub kroneckerproduct '(a,b)
m=ubound(a,1): n=ubound(a,2)
p=ubound(b,1): q=ubound(b,2)
rtn=m*p
ctn=n*q
redim r(rtn,ctn)
for i=1 to m
for j=1 to n
for k=1 to p
for l=1 to q
r(p*(i-1)+k,q*(j-1)+l)=a(i,j)*b(k,l)
next: next: next: next
end sub 'kroneckerproduct
Private Sub printmatrix(text, m, w)
wscript.stdout.writeline text
Dim myArr()
Select Case m
Case "a": myArr = a()
Case "b": myArr = b()
Case "r": myArr = r()
End Select
For i = LBound(myArr, 1) To UBound(myArr, 1)
text = vbNullString
For j = LBound(myArr, 2) To UBound(myArr, 2)
Select Case m
Case "a": k = a(i, j)
Case "b": k = b(i, j)
Case "r": k = r(i, j)
End Select
text = text & " " & k
Next
wscript.stdout.writeline text
Next
End Sub 'printmatrix
 
sub printall(w)
printmatrix "matrix a:", "a", w
printmatrix "matrix b:", "b", w
printmatrix "kronecker product:", "r", w
end sub 'printall
sub main()
xa = Array(1, 2, _
3, 4)
ReDim a(LBound(xa, 1) To LBound(xa, 1) + 1, LBound(xa, 1) To LBound(xa, 1) + 1)
k = LBound(a, 1)
For i = LBound(a, 1) To UBound(a, 1): For j = LBound(a, 1) To UBound(a, 1)
a(i, j) = xa(k): k = k + 1
Next: Next
xb = Array(0, 5, _
6, 7)
ReDim b(LBound(xb, 1) To LBound(xb, 1) + 1, LBound(xb, 1) To LBound(xb, 1) + 1)
k = LBound(b, 1)
For i = LBound(b, 1) To UBound(b, 1): For j = LBound(b, 2) To UBound(b, 2)
b(i, j) = xb(k): k = k + 1
Next: Next
kroneckerproduct
printall 3
 
xa = 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)
k = LBound(a, 1)
For i = LBound(a, 1) To UBound(a, 1): For j = LBound(a, 1) To UBound(a, 1)
a(i, j) = xa(k): k = k + 1
Next: Next
xb = Array(1, 1, 1, 1, _
1, 0, 0, 1, _
1, 1, 1, 1)
ReDim b(LBound(xb, 1) To LBound(xb, 1) + 2, LBound(xb, 1) To LBound(xb, 1) + 3)
k = LBound(b, 1)
For i = LBound(b, 1) To UBound(b, 1): For j = LBound(b, 2) To UBound(b, 2)
b(i, j) = xb(k): k = k + 1
Next: Next
 
kroneckerproduct
printall 2
end sub 'main
 
main</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|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-matrix}}
The above module already includes a method to calculate the Kronecker product.
<syntaxhighlight lang="wren">import "./fmt" for Fmt
import "./matrix" for Matrix
 
var a1 = [
[1, 2],
[3, 4]
]
 
var a2 = [
[0, 5],
[6, 7]
]
 
var a3 = [
[0, 1, 0],
[1, 1, 1],
[0, 1, 0]
]
 
var a4 = [
[1, 1, 1, 1],
[1, 0, 0, 1],
[1, 1, 1, 1]
]
 
var m1 = Matrix.new(a1)
var m2 = Matrix.new(a2)
Fmt.mprint(m1.kronecker(m2), 2, 0)
System.print()
var m3 = Matrix.new(a3)
var m4 = Matrix.new(a4)
Fmt.mprint(m3.kronecker(m4), 2, 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|
═══════ matrix Kronecker product ═══════
| 0 0 0 0 1 0 0 1 0 0 0 0|
| 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0|
| 1 1 1 1 0 01 0 01 1 0 01 1 0 01 0 01 1|
| 1 0 0 1 0 01 0 0 1 1 1 1 0 0 0 0 1|
| 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1|
| 0 0 0 0 1 0 01 1 1 0 0 1 1 0 0 1 0|
| 0 0 0 0 1 1 1 10 1 10 1 1 1 10 1 10 0 0|
| 0 0 0 0 0 0 1 1 1 1 0 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|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 857 ⟶ 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 868 ⟶ 5,083:
1,0,0,1,
1,1,1,1);
kronecker(A,B).format(2,0).println();</langsyntaxhighlight>
{{out}}
<pre>
2,169

edits