Extract a diagonal.
SciPhp\NdArray
NumPhp::diagonal(
mixed
$array
,
int
$k = 0
)
$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::diagonal($m);
// Extract diagonal with offset 1
$diagonalPosOffset = np::diagonal($m, 1);
// Extract diagonal with offset -1
$diagonalNegOffset = np::diagonal($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]