NdArray::sum

Sum all elements.

Description

float|int| SciPhp\NdArray NdArray::sum( [ int $axis = null ] [, bool $keepdims = false ])

Parameters

$axis
An integer. Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array.
$keepdims
A boolean. If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

Return Values

A float or an integer.

Examples

Example #1: Sum a square matrix

use SciPhp\NumPhp as np;

$m np::linspace(199)->reshape(33);

$s $m->sum();

echo 
"m\n$m""s=sum(m)\n$s";

The above example will output:

m
[[1  2  3]
 [4  5  6]
 [7  8  9]]
s=sum(m)
45

Example #2: Sum a square matrix on different axis

use SciPhp\NumPhp as np;

$m np::linspace(199)->reshape(33);

// Sum over axis 0
$s0 $m->sum(0);

// Sum over axis 1
$s1 $m->sum(1);

echo 
"m\n$m""s0=$s0""s1=$s1";

The above example will output:

m
[[1  2  3]
 [4  5  6]
 [7  8  9]]

s0=[12  15  18]
s1=[6   15  24]

Example #3: Sum a square matrix on different axis with keepdims = true

use SciPhp\NumPhp as np;

$m np::linspace(199)->reshape(33);

// Sum over axis 0 and keepdims = true
$s0 $m->sum(0true);

// Sum over axis 1 and keepdims = true
$s1 $m->sum(1true);

echo 
"m\n$m""s0=$s0""s1=$s1";

The above example will output:

m
[[1  2  3]
 [4  5  6]
 [7  8  9]]

s0=[[12  15  18]]
s1=
[[6 ]
 [15]
 [24]]

See Also