Function Repository Resource:

Broadcasting

Source Notebook

Calculate multidimensional arrays according to the broadcasting rules of NumPy

Contributed by: Aster Ctor

ResourceFunction["Broadcasting"][expression]

calculates a multidimensional array from expression using the broadcasting rules.

ResourceFunction["Broadcasting"][op]

converts an op to a ResourceFunction["Broadcasting"] operator.

Details and Options

ResourceFunction["Broadcasting"] makes the result of a listable operation agree with NumPy.

Examples

Basic Examples (3) 

In NumPy, multidimensional array operations are tail-aligned:

In[1]:=
ExternalEvaluate["Python", "from numpy import zeros,ones
(zeros((8,5,7,4))+ones((7,4))).shape"]
Out[1]=

Here this alignment is not supported:

In[2]:=
Array[0 &, {8, 5, 7, 4}] + Array[1 &, {7, 4}] // Dimensions
Out[2]=

Use Broadcasting to achieve the same effect as in NumPy:

In[3]:=
ResourceFunction["Broadcasting"][
  Array[0 &, {8, 5, 7, 4}] + Array[1 &, {7, 4}]] // Dimensions
Out[3]=

Scope (3) 

Plus does not thread over arrays of different dimensions:

In[4]:=
Plus[{{x, y}, {z, w}}, {{a}, {b}}, c]
Out[4]=

Define the Broadcasting Plus operator:

In[5]:=
bPlus = ResourceFunction["Broadcasting"][Plus];

Now this kind of operation can be done:

In[6]:=
bPlus[{{x, y}, {z, w}}, {{a}, {b}}, c]
Out[6]=

Properties and Relations (2) 

Listable functions in the Wolfram Language can effectively thread when initial dimensions match:

In[7]:=
Array[0 &, {4, 7, 5, 8}] + Array[1 &, {4, 7}] // Dimensions
Out[7]=

NumPy does not support this initial alignment:

In[8]:=
ExternalEvaluate["Python", "from numpy import zeros,ones
(zeros((4,7,5,8))+ones((4,7))).shape"]
Out[8]=

Possible Issues (1) 

If dimensions are not broadcastable, then Broadcasting will report an error and will not return any results:

In[9]:=
ResourceFunction["Broadcasting"][Plus][Array[a, {3}], Array[b, {4, 2}]]

Publisher

Aster Ctor (MoeNet)

Version History

  • 1.0.0 – 18 November 2019

Author Notes

The nested operation is not supported now.

License Information