NumPhp::broadcast_to

Broadcast an array to a new shape.

Description

SciPhp\NdArray NumPhp::broadcast_to( array|NdArray $m , array $shape )

Parameters

$m
An array [1, 2, 3] or a NdArray.
$shape
An array [1, 2, 3] of integers which represents the shape of the created NdArray.

Return Values

A new SciPhp\NdArray

Examples

Example #1: Adding a dimension

use SciPhp\NumPhp as np;

$x np::broadcast_to([123], [13]);

echo 
$x;

The above example will output:

x
[[1  2  3]]

Example #2: Broadcast a 1-dim (3,) to 2-dim (3,3)

use SciPhp\NumPhp as np;

$x np::broadcast_to([123], [33]);

echo 
"x\n$x";

The above example will output:

x
[[1  2  3]
 [1  2  3]
 [1  2  3]]

Example #3: Broadcast a 2-dim (3,1) to 2-dim (3,3) matrix

use SciPhp\NumPhp as np;

$x np::broadcast_to(
    [[
1],
     [
2],
     [
3]],
    [
33]
);

echo 
"x\n$x";

The above example will output:

x
[[1  1  1]
 [2  2  2]
 [3  3  3]]

Example #4: A broadcast failure throws an InvalidArgumentException

use SciPhp\NumPhp as np;

$x np::broadcast_to([123], [31]);

The above example will output:

InvalidArgumentException: Arrays could not be broadcast together with 
remapped shapes [original->remapped]: [3] and requested shape [3  1]

See Also