Extract a diagonal or construct a diagonal array.
SciPhp\NdArray
NumPhp::diag(
mixed
$array
,
int
$k = 0
)
If parameter is a 1D array (NdArray or a PHP array), it is taken as a diagonal to create a n*n matrix. If parameter is a 2D array, its diagonal is extracted.
$array
$k
use SciPhp\NumPhp as np;
// Construct a 3*3 matrix
$m = np::linspace(1, 9, 9)->reshape(3, 3);
// Extract default diagonal
$diagonal = np::diag($m);
// Extract diagonal with offset 1
$diagonalPosOffset = np::diag($m, 1);
// Extract diagonal with offset -1
$diagonalNegOffset = np::diag($m, -1);
echo "
Matrix:
$m
Diagonal:
$diagonal
Diagonal with offset=1:
$diagonalPosOffset
Diagonal with offset=-1:
$diagonalNegOffset
";
The above example will output:
Matrix: [[1 2 3] [4 5 6] [7 8 9]] Diagonal: [1 5 9] Diagonal with offset=1: [2 6] Diagonal with offset=-1: [4 8]
// Construct a 3*3 matrix
$m3x3 = np::diag([1, 2, 3]);
// Construct a 3*4 matrix
$m3x4 = np::diag([1, 2, 3], 1);
// Construct a 4*3 matrix
$m4x3 = np::diag([1, 2, 3], -1);
echo "
Matrix 3*3:
$m3x3
Matrix 3*4:
$m3x4
Matrix 4*3:
$m4x3
";
The above example will output:
Matrix 3*3: [[1 0 0] [0 2 0] [0 0 3]] Matrix 3*4: [[0 1 0 0] [0 0 2 0] [0 0 0 3]] Matrix 4*3: [[0 0 0] [1 0 0] [0 2 0] [0 0 3]]