Kronecker product: Difference between revisions

jq
m (→‎{{header|REXX}}: fixed two typos.)
(jq)
Line 1,268:
[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.
<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));
 
reduce range(0; a|length) as $j ([];
. + reduce range(0; a[0]|length) as $i ([];
addblock( b | multiply(a[$j][$i]) ) ));</lang>
 
Examples:
<lang jq>
def left: [[ 1, 2], [3, 4]];
def right: [[ 0, 5], [6, 7]];
 
kprod(left;right)</lang>
{{out}}
<pre>[[0,5,0,10],[6,7,12,14],[0,15,0,20],[18,21,24,28]]</pre>
 
<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)</lang>
{{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|Kotlin}}==
2,502

edits