Block-diagonal matrix from columns
MATL, 6 bytes
"@N$Yd
Works in current version (13.0.0) of the language/compiler.
Input has the following form, with semicolon as row separator, and commas or spaces as column separators within each row:
[1, 2, 3; 4, 5, 6]
Try it online!
Explanation
" % implicitly input 2D array and loop over its columns
@ % push column
N$Yd % build block-diagonal matrix from all stack contents. Stack contents are
% a single column in the first iteration, or a partially built 2D array
% and a new column in all other iterations
% end loop
% implicit display
Worked example
Consider the input [1 2 3; 4 5 6]
. The for loop beginning with "
takes each column of the input. Within each iteration, @
pushes the current column onto the stack. So in the first iteration it pushes [1; 4]
. N$
specifies that all the stack contents will be used as inputs of the following function, Yd
.
This function (corresponding to MATLAB's blkdiag
) "diagonally concatenates" its inputs to produce a block diagonal matrix (2D array). So in the first iteration Yd
it takes one input and produces an output equal to that input, [1; 4]
, which is left on the stack.
In the second iteration the second column of the input, [2; 5]
, is pushed. Now Yd
takes two 2×1 inputs, namely [1; 4]
and [2; 5]
, and produces the 4×2 array [1 0; 4 0; 0 2; 0 5]
.
In the third iteration Yd
takes the latter 4×2 array and the third column of the input, [3; 6]
, and produces the final result [1 0 0; 4 0 0; 0 2 0; 0 5 0; 0 0 3; 0 0 6]
.
ES6, 65 bytes
a=>[].concat(...a[0].map((_,i)=>a.map(b=>b.map((c,j)=>i-j?0:c))))
Takes as input and returns as output an array of arrays.
Mathematica, 40 39 Bytes
Credit to @Seeq for Infix
ing Flatten
.
Transpose[DiagonalMatrix/@#]~Flatten~1&
Input is a list of row vectors delimited by {}
brackets. So the initial example is represented by
{{1,2,3},{4,5,6}}
Generate an array of DiagonalMatrix
where each one has diagonal elements from the rows of the input (3-D array). Transpose
so the Flatten
operation removes the correct bracket pairs to give the desired matrix (now 2-D array).