NumPhp::diagonal

Extract a diagonal.

Description

SciPhp\NdArray NumPhp::diagonal( 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: Extracting diagonals

use SciPhp\NumPhp as np;

// Construct a 3*3 matrix
$m np::linspace(199)->reshape(33);

// Extract default diagonal
$diagonal np::diagonal($m);

// Extract diagonal with offset 1
$diagonalPosOffset np::diagonal($m1);

// 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]

See Also