NumPhp::diagflat

Create a two-dimensional array with the flattened input as a diagonal.

Description

SciPhp\NdArray NumPhp::diagflat( mixed $array , int $k = 0 )

Parameters

$array
An array [1, 2, 3] or a NdArray.
$k
Default value is 0. It's an offset.

Return Values

A SciPhp\NdArray

Examples

Example #1: Construct a diagonal array


// Construct a 2*2 matrix which will be flattened
$x np::linspace(144)->reshape(22);

// Construct a 4*4 matrix
$m4x4 np::diagflat($x);

// Construct a 4*5 matrix
$m4x5 np::diagflat($x1);

// Construct a 5*4 matrix
$m5x4 np::diagflat($x, -1);

echo 
"
Original x
$x
Matrix 4*4:
$m4x4
Matrix 4*5:
$m4x5
Matrix 5*4:
$m5x4
"
;

The above example will output:

Original x
[[1  2]
 [3  4]]

Matrix 4*4:
[[1  0  0  0]
 [0  2  0  0]
 [0  0  3  0]
 [0  0  0  4]]

Matrix 4*5:
[[0  1  0  0  0]
 [0  0  2  0  0]
 [0  0  0  3  0]
 [0  0  0  0  4]]

Matrix 5*4:
[[0  0  0  0]
 [1  0  0  0]
 [0  2  0  0]
 [0  0  3  0]
 [0  0  0  4]]

See Also