NumPhp::diag

Extract a diagonal or construct a diagonal array.

Description

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.

Parameters

$array
An array [1, 2, 3] or a NdArray.
$k
Default value is 0. Diagonal 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::diag($m);

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

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

Example #2: Construct a diagonal array


// Construct a 3*3 matrix
$m3x3 np::diag([123]);

// Construct a 3*4 matrix
$m3x4 np::diag([123], 1);

// Construct a 4*3 matrix
$m4x3 np::diag([123], -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]]

See Also