NumPhp::sum

Sum all elements.

Description

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

Parameters

$m
An array [1, 2, 3] or a NdArray.
$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 np::sum($m);

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 np::sum($m0);

// Sum over axis 1
$s1 np::sum($m1);

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 np::sum($m0true);

// Sum over axis 1 and keepdims = true
$s1 np::sum($m1true);

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