NdArray::trace

Sum along diagonals.

Description

float|int NdArray::trace( int $k = 0 )

Parameters

$k
Default value is 0. Diagonal offset.

Return Values

A float|int

Examples

Example #1: Calculate default trace

use SciPhp\NumPhp as np;

$m np::arange(09)->reshape(33);

$r $m->trace();

echo 
"m\n$m""r\n$r";

The above example will output:

m
[[0  1  2]
 [3  4  5]
 [6  7  8]]
r
12

Example #2: Calculate a trace with an offset

use SciPhp\NumPhp as np;

$m np::arange(09)->reshape(33);

$r $m->trace(1);

echo 
"m\n$m""r\n$r";

The above example will output:

m
[[0  1  2]
 [3  4  5]
 [6  7  8]]
r
6

See Also

  • NumPhp::diagonal() - Extract a diagonal.
  • NumPhp::diag() - Extract a diagonal or construct a diagonal array.
  • NumPhp::diagflat() - Create a two-dimensional array with the flattened input as a diagonal.
  • NumPhp::eye() - Construct a 2-D array with ones on the diagonal and zeros elsewhere.
  • NumPhp::identity() - Construct a square 2-D array with ones on the diagonal and zeros elsewhere.
  • NdArray::prod() - Documentation does NOT exist for this function
  • NdArray::sum() - Sum all elements.