Kronecker product: Difference between revisions
m
syntax highlighting fixup automation
Alpha bravo (talk | contribs) (Added AutoHotkey) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 49:
{{trans|Python}}
<
V b1 = [[0, 5], [6, 7]]
Line 82:
V result2 = kronecker(a2, b2)
L(elem) result2
print(elem)</
{{out}}
Line 103:
=={{header|360 Assembly}}==
<
KRONECK CSECT
USING KRONECK,R13 base register
Line 244:
R DS (NR*NR)F r(nr,nr)
YREGS
END KRONECK</
{{out}}
<pre>
Line 266:
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}}
<
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
Line 405:
Test1()
Test2()
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Kronecker_product.png Screenshot from Atari 8-bit computer]
Line 434:
{{works with|Ada|Ada|83}}
<
with Ada.Integer_Text_IO;
Line 488:
Ada.Text_IO.New_Line;
end loop;
end Kronecker_Product;</
{{out}}
<pre> 0 5 0 10
Line 507:
=={{header|ALGOL 68}}==
<
# multiplies in-place the elements of the matrix a by the scaler b #
OP *:= = ( REF[,]INT a, INT b )REF[,]INT:
Line 569:
)
END
</syntaxhighlight>
{{out}}
<pre>
Line 590:
=={{header|APL}}==
{{works with|Dyalog APL}}
<
{{out}}
Line 618:
└─────┴───────┴───────────────────────┘</pre>
=={{header|AppleScript}}==
<
-- kprod :: [[Num]] -> [[Num]] -> [[Num]]
Line 805:
on unlines(xs)
intercalate(linefeed, xs)
end unlines</
{{Out}}
<pre>{0, 5, 0, 10}
Line 824:
=={{header|Arturo}}==
{{trans|Kotlin}}
<
print: [
result: ""
Line 875:
print "Kronecker Product:"
print kroneckerProduct A2 B2</
{{out}}
Line 915:
=={{header|AutoHotkey}}==
<
prod := [], r:= 1, c := 1
for i, aa in a
Line 926:
}
return prod
}</
Examples:<
b := [[0, 5], [6, 7]]
P := KroneckerProduct(a, b)
Line 951:
MsgBox % result
return
</syntaxhighlight>
{{out}}
<pre>0 5 0 10
Line 969:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f KRONECKER_PRODUCT.AWK
BEGIN {
Line 1,035:
return(n)
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,078:
=={{header|BQN}}==
<syntaxhighlight lang
or
<syntaxhighlight lang
Example:
<
r ← >⟨0‿5, 6‿7⟩
l KProd r</
<pre>
Line 1,105:
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>
Line 1,181:
printf("\n\n\nKronecker product of the two matrices written to %s.",output);
}
</syntaxhighlight>
Input file :
Line 1,220:
=={{header|C sharp}}==
<
using System.Collections;
using System.Collections.Generic;
Line 1,273:
}
}</
{{out}}
<pre>
Line 1,292:
=={{header|C++}}==
<
#include <iomanip>
#include <iostream>
Line 1,390:
test2();
return 0;
}</
{{out}}
Line 1,417:
=={{header|D}}==
{{Trans|Go}}
<syntaxhighlight lang="d">
import std.stdio, std.outbuffer;
Line 1,471:
sample(C,D);
}
</syntaxhighlight>
Output:
Line 1,513:
=={{header|Factor}}==
{{works with|Factor|0.99 2020-01-23}}
<
{ { 1 2 } { 3 4 } }
Line 1,519:
{ { 0 1 0 } { 1 1 1 } { 0 1 0 } }
{ { 1 1 1 1 } { 1 0 0 1 } { 1 1 1 1 } }
[ kronecker-product . ] 2bi@</
{{out}}
<pre>
Line 1,539:
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. <
CONTAINS !For the specific problem only.
SUBROUTINE KPRODUCT(A,B,AB) !AB = Kronecker product of A and B, both two-dimensional arrays.
Line 1,595:
CALL SHOW (6,AB)
END</
Output:
Line 1,619:
</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, <
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 1,672:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>[ 0 5 0 10]
Line 1,691:
=={{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.
<
b = [[0,5],[6,7]]
println[formatProd[a,b]]
Line 1,713:
return n
}</
{{out}}
<pre>
Line 1,756:
=={{header|Go}}==
===Implementation===
<
import (
Line 1,828:
{1, 1, 1, 1},
})
}</
{{out}}
<pre>
Line 1,863:
===Library go.matrix===
<
import (
Line 1,893:
{1, 1, 1, 1},
})))
}</
{{out}}
<pre>
Line 1,913:
===Library gonum/matrix===
Gonum/matrix doesn't have the Kronecker product, but here's an implementation using available methods.
<
import (
Line 1,956:
1, 1, 1, 1,
}))))
}</
{{out}}
<pre>
Line 1,976:
=={{header|Haskell}}==
<
-------------------- KRONECKER PRODUCT -------------------
Line 2,003:
[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
[[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]]
)</
{{Out}}
<pre>[0,5,0,10]
Line 2,026:
Explicit implementation:
<
Tacit:
<
these definitions are functionally equivalent.
Line 2,036:
Task examples:
<
N=: (+4**)i.2 2
P=: -.0 2 6 8 e.~i.3 3
Line 2,054:
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</
=={{header|Java}}==
<syntaxhighlight lang="java">
package kronecker;
Line 2,203:
}
</syntaxhighlight>
{{Output}}
Line 2,252:
====Version #1.====
{{Works with|Chrome}}
<
// matkronprod.js
// Prime function:
Line 2,270:
}
}
</
;Required tests:
<
<!-- KronProdTest.html -->
<html><head>
Line 2,292:
</head><body></body>
</html>
</
{{Output}} '''Console and page results'''
<pre>
Line 2,332:
{{trans|PARI/GP}}
{{Works with|Chrome}}
<
// matkronprod2.js
// Prime function:
Line 2,363:
}
}
</
;Required tests:
<
<!-- KronProdTest2.html -->
<html><head>
Line 2,384:
</head><body></body>
</html>
</
{{Output}} '''Console and page results'''
Line 2,395:
{{Trans|Haskell}}
(As JavaScript is now widely embedded in non-browser contexts, a non-HTML string value is returned here, rather than making calls to methods of the Document Object Model, which is not part of JavaScript and will not always be available to a JavaScript interpreter)
<
'use strict';
Line 2,481:
// MAIN ---
console.log(main());
})();</
{{Out}}
<pre>[0,5,0,10]
Line 2,500:
=={{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.
<
# element-wise multiplication of a matrix by a number, "c"
Line 2,517:
| reduce range(0; a|length) as $i ([];
. + reduce range(0; $m) as $j ([];
addblock( b | multiply(a[$i][$j]) ) ));</
Examples:
<syntaxhighlight lang="jq">
def left: [[ 1, 2], [3, 4]];
def right: [[ 0, 5], [6, 7]];
kprod(left;right)</
{{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)</
{{out}}
<pre>[[0,0,0,0,1,1,1,1,0,0,0,0],
Line 2,546:
=={{header|Julia}}==
<
# Julia has a builtin kronecker product function
Line 2,564:
for row in 1:size(k)[1]
println(k[row,:])
end</
{{out}}
Line 2,586:
=={{header|Kotlin}}==
{{trans|JavaScript (Imperative #2)}}
<
typealias Matrix = Array<IntArray>
Line 2,645:
r = kroneckerProduct(a, b)
printAll(a, b, r)
}</
{{out}}
Line 2,686:
=={{header|Lua}}==
<
function prod( a, b )
print( "\nPRODUCT:" )
Line 2,706:
b = { { 1, 1, 1, 1 }, { 1, 0, 0, 1 }, { 1, 1, 1, 1 } }
prod( a, b )
</syntaxhighlight>
{{out}}
<pre>
Line 2,728:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
KroneckerProduct[{{0, 1, 0}, {1, 1, 1}, {0, 1, 0}},
{{1, 1, 1, 1}, {1, 0, 0, 1}, {1, 1, 1, 1}}]//MatrixForm</
{{out}}
<pre>0 5 0 10
Line 2,750:
Same as Kotlin but with a generic Matrix type.
<
type Matrix[M, N: static Positive; T: SomeNumber] = array[M, array[N, T]]
Line 2,788:
echo "Matrix A:\n", A2
echo "Matrix B:\n", B2
echo "Kronecker product:\n", kroneckerProduct(A2, B2)</
{{out}}
Line 2,827:
=={{header|Octave}}==
<
ans =
Line 2,846:
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</
=={{header|PARI/GP}}==
=== Version #1 ===
{{Works with|PARI/GP|2.9.1 and above}}
<
\\ Print title and matrix mat rows. 4/17/16 aev
matprows(title,mat)={print(title); for(i=1,#mat[,1], print(mat[i,]))}
Line 2,879:
matprows("Sample 2 result:",r);
}
</
{{Output}}
Line 2,902:
This version is from B. Allombert. 12/12/17
{{Works with|PARI/GP|2.9.1 and above}}
<
\\ Print title and matrix mat rows. aev
matprows(title,mat)={print(title); for(i=1,#mat[,1], print(mat[i,]))}
Line 2,921:
matprows("Sample 2 result:",r);
}
</
{{Output}}
Line 2,943:
=={{header|Perl}}==
<
use strict;
use warnings;
Line 2,968:
print "B = $mat->[1]\n";
print "kron(A,B) = " . kron($mat->[0], $mat->[1]) . "\n";
}</
=={{header|Phix}}==
<!--<
<span style="color: #008080;">function</span> <span style="color: #000000;">kronecker</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ar</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">),</span>
Line 3,007:
<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>
<!--</
{{out}}
<pre>
Line 3,028:
{{trans|Python}}
<
array final_list = ({});
array sub_list = ({});
Line 3,081:
return 0;
}</
{{out}}
<pre>0 5 0 10
Line 3,099:
=={{header|PureBasic}}==
<
DataSection
Matrix_A_B_Dimension_Bsp1:
Line 3,206:
Bsp2_Matrix_A_B:
Restore Matrix_A_B_Dimension_Bsp2
Return</
{{out}}
<pre>Matrix A:
Line 3,249:
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.
<
# Sample 1
Line 3,289:
result2 = kronecker(a2, b2)
for elem in result2:
print(elem)</
Result:
Line 3,312:
Code:
<
r = [[1, 2], [3, 4]]
s = [[0, 5], [6, 7]]
Line 3,330:
# Result 2
for row in kronecker(t, u):
print(row)</
===Version 3===
Line 3,342:
(Versions 2 and 3 produce the same output from the same test)
<
Line 3,387:
# Result 2
for row in kronecker(t, u):
print(row)</
{{Out}}
<pre>[0, 5, 0, 10]
Line 3,406:
=={{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>
Line 3,427:
Uses typed racket, since the 'math/...' libraries are much more performant in that language.
<
(require math/array
Line 3,459:
(matrix [[1 1 1 1]
[1 0 0 1]
[1 1 1 1]])))</
{{out}}
Line 3,477:
(formerly Perl 6)
{{works with|rakudo|2017.01-34-g700a077}}
<syntaxhighlight lang="raku"
return (@a X @b).map: { .[0].list X* .[1].list };
}
Line 3,486:
.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>
{{out}}
<pre>(0 5 0 10)
Line 3,505:
=={{header|REXX}}==
A little extra coding was added to make the matrix glyphs and elements alignment look nicer.
<
w= 0 /*W: max width of any matrix element. */
aMat= 2x2 1 2 3 4 /*define A matrix size and elements.*/
Line 3,549:
say $ $ _ '│' /*append a long vertical bar. */
end /*r*/
say $ $ translate(z, '└┘', "┌┐"); return /*show the bot part of matrix.*/</
{{out|output|text= when using the default inputs:}}
<pre>
Line 3,604:
=={{header|Ring}}==
<
# Project : Kronecker product
Line 3,650:
next
next
</syntaxhighlight>
Output:
<pre>
Line 3,671:
=={{header|Rust}}==
<
let mut a = vec![vec![1., 2.], vec![3., 4.]];
Line 3,764:
matrix
}
</syntaxhighlight>
{{out}}
<pre>
Line 3,815:
=={{header|Scala}}==
<
{
/**Get the dimensions of the input matrix*/
Line 3,856:
}
</syntaxhighlight>
{{out}}
<pre>
Line 3,877:
=={{header|Sidef}}==
{{trans|Raku}}
<
a ~X b -> map { _[0] ~X* _[1] }
}
Line 3,886:
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 }</
{{out}}
<pre>
Line 3,906:
=={{header|Simula}}==
<
PROCEDURE OUTMATRIX(A, W); INTEGER ARRAY A; INTEGER W;
Line 4,056:
END EXAMPLE 2;
END</
{{out}}
<pre>
Line 4,094:
In Mata, the Kronecker product is the operator '''#'''.
<
------------------------------------------------- mata (type end to exit) ----------
: a=1,2\3,4
Line 4,126:
9 | 0 0 0 0 1 1 1 1 0 0 0 0 |
+-------------------------------------------------------------+
: end</
=={{header|SuperCollider}}==
<
(
f = { |a, b|
Line 4,168:
(a *.2 b).collect(_.reduce('+++')).reduce('++')
</syntaxhighlight>
<
(
x = f.(
Line 4,185:
)
)
</syntaxhighlight>
Results in:
Line 4,205:
And:
<syntaxhighlight lang="supercollider">(
x = f.(
[
Line 4,217:
)
)
</syntaxhighlight>
returns:
Line 4,231:
=={{header|Swift}}==
<
let m = m1.count
let n = m1[0].count
Line 4,308:
]
printProducts(a: a2, b: b2)</
{{out}}
Line 4,344:
=={{header|Tcl}}==
<
proc parse_matrix {s} {
split [string trim $s] \n
Line 4,408:
print_matrix [kroenecker $a $b]
puts ""
}</
{{out}}
Line 4,428:
=={{header|VBScript}}==
<
dim a(),b(),r()
Line 4,505:
end sub 'main
main</
{{out}}
<pre>
Line 4,543:
{{libheader|Wren-matrix}}
The above module already includes a method to calculate the Kronecker product.
<
import "/matrix" for Matrix
Line 4,574:
var m3 = Matrix.new(a3)
var m4 = Matrix.new(a4)
Fmt.mprint(m3.kronecker(m4), 2, 0)</
{{out}}
Line 4,595:
=={{header|zkl}}==
<
fcn kronecker(A,B){
m,n, p,q := A.rows,A.cols, B.rows,B.cols;
Line 4,601:
foreach i,j,k,l in (m,n,p,q){ r[p*i + k, q*j + l]=A[i,j]*B[k,l] }
r
}</
<
B:=GSL.Matrix(2,2).set(0,5, 6,7);
kronecker(A,B).format(3,0).println(); // format(width,precision)
Line 4,612:
1,0,0,1,
1,1,1,1);
kronecker(A,B).format(2,0).println();</
{{out}}
<pre>
|