<html lang="en"> <head> <title>Broadcasting - GNU Octave</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="GNU Octave"> <meta name="generator" content="makeinfo 4.13"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Vectorization-and-Faster-Code-Execution.html#Vectorization-and-Faster-Code-Execution" title="Vectorization and Faster Code Execution"> <link rel="prev" href="Basic-Vectorization.html#Basic-Vectorization" title="Basic Vectorization"> <link rel="next" href="Function-Application.html#Function-Application" title="Function Application"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <a name="Broadcasting"></a> <p> Next: <a rel="next" accesskey="n" href="Function-Application.html#Function-Application">Function Application</a>, Previous: <a rel="previous" accesskey="p" href="Basic-Vectorization.html#Basic-Vectorization">Basic Vectorization</a>, Up: <a rel="up" accesskey="u" href="Vectorization-and-Faster-Code-Execution.html#Vectorization-and-Faster-Code-Execution">Vectorization and Faster Code Execution</a> <hr> </div> <h3 class="section">19.2 Broadcasting</h3> <p><a name="index-broadcast-2126"></a><a name="index-broadcasting-2127"></a><a name="index-BSX-2128"></a><a name="index-recycling-2129"></a><a name="index-SIMD-2130"></a> Broadcasting refers to how Octave binary operators and functions behave when their matrix or array operands or arguments differ in size. Since version 3.6.0, Octave now automatically broadcasts vectors, matrices, and arrays when using elementwise binary operators and functions. Broadly speaking, smaller arrays are “broadcast” across the larger one, until they have a compatible shape. The rule is that corresponding array dimensions must either <ol type=1 start=1> <li>be equal, or <li>one of them must be 1. </ol> <p class="noindent">In case all dimensions are equal, no broadcasting occurs and ordinary element-by-element arithmetic takes place. For arrays of higher dimensions, if the number of dimensions isn't the same, then missing trailing dimensions are treated as 1. When one of the dimensions is 1, the array with that singleton dimension gets copied along that dimension until it matches the dimension of the other array. For example, consider <pre class="example"> x = [1 2 3; 4 5 6; 7 8 9]; y = [10 20 30]; x + y </pre> <p class="noindent">Without broadcasting, <code>x + y</code> would be an error because the dimensions do not agree. However, with broadcasting it is as if the following operation were performed: <pre class="example"> x = [1 2 3 4 5 6 7 8 9]; y = [10 20 30 10 20 30 10 20 30]; x + y ⇒ 11 22 33 14 25 36 17 28 39 </pre> <p class="noindent">That is, the smaller array of size <code>[1 3]</code> gets copied along the singleton dimension (the number of rows) until it is <code>[3 3]</code>. No actual copying takes place, however. The internal implementation reuses elements along the necessary dimension in order to achieve the desired effect without copying in memory. <p>Both arrays can be broadcast across each other, for example, all pairwise differences of the elements of a vector with itself: <pre class="example"> y - y' ⇒ 0 10 20 -10 0 10 -20 -10 0 </pre> <p class="noindent">Here the vectors of size <code>[1 3]</code> and <code>[3 1]</code> both get broadcast into matrices of size <code>[3 3]</code> before ordinary matrix subtraction takes place. <p>A special case of broadcasting that may be familiar is when all dimensions of the array being broadcast are 1, i.e. the array is a scalar. Thus for example, operations like <code>x - 42</code> and <code>max (x, 2)</code> are basic examples of broadcasting. <p>For a higher-dimensional example, suppose <code>img</code> is an RGB image of size <code>[m n 3]</code> and we wish to multiply each color by a different scalar. The following code accomplishes this with broadcasting, <pre class="example"> img .*= permute ([0.8, 0.9, 1.2], [1, 3, 2]); </pre> <p class="noindent">Note the usage of permute to match the dimensions of the <code>[0.8, 0.9, 1.2]</code> vector with <code>img</code>. <p>For functions that are not written with broadcasting semantics, <code>bsxfun</code> can be useful for coercing them to broadcast. <!-- bsxfun src/DLD-FUNCTIONS/bsxfun.cc --> <p><a name="doc_002dbsxfun"></a> <div class="defun"> — Loadable Function: <b>bsxfun</b> (<var>f, A, B</var>)<var><a name="index-bsxfun-2131"></a></var><br> <blockquote><p>The binary singleton expansion function applier performs broadcasting, that is, applies a binary function <var>f</var> element-by-element to two array arguments <var>A</var> and <var>B</var>, and expands as necessary singleton dimensions in either input argument. <var>f</var> is a function handle, inline function, or string containing the name of the function to evaluate. The function <var>f</var> must be capable of accepting two column-vector arguments of equal length, or one column vector argument and a scalar. <p>The dimensions of <var>A</var> and <var>B</var> must be equal or singleton. The singleton dimensions of the arrays will be expanded to the same dimensionality as the other array. <!-- Texinfo @sp should work but in practice produces ugly results for HTML. --> <!-- A simple blank line produces the correct behavior. --> <!-- @sp 1 --> <p class="noindent"><strong>See also:</strong> <a href="doc_002darrayfun.html#doc_002darrayfun">arrayfun</a>, <a href="doc_002dcellfun.html#doc_002dcellfun">cellfun</a>. </p></blockquote></div> <p>Broadcasting is only applied if either of the two broadcasting conditions hold. As usual, however, broadcasting does not apply when two dimensions differ and neither is 1: <pre class="example"> x = [1 2 3 4 5 6]; y = [10 20 30 40]; x + y </pre> <p class="noindent">This will produce an error about nonconformant arguments. <p>Besides common arithmetic operations, several functions of two arguments also broadcast. The full list of functions and operators that broadcast is <pre class="example"> plus + .+ minus - .- times .* rdivide ./ ldivide .\ power .^ .** lt < le <= eq == gt > ge >= ne != ~= and & or | atan2 hypot max min mod rem xor += -= .+= .-= .*= ./= .\= .^= .**= &= |= </pre> <p>Beware of resorting to broadcasting if a simpler operation will suffice. For matrices <var>a</var> and <var>b</var>, consider the following: <pre class="example"> <var>c</var> = sum (permute (<var>a</var>, [1, 3, 2]) .* permute (<var>b</var>, [3, 2, 1]), 3); </pre> <p class="noindent">This operation broadcasts the two matrices with permuted dimensions across each other during elementwise multiplication in order to obtain a larger 3-D array, and this array is then summed along the third dimension. A moment of thought will prove that this operation is simply the much faster ordinary matrix multiplication, <var>c</var><code> = </code><var>a</var><code>*</code><var>b</var><code>;</code>. <p>A note on terminology: “broadcasting” is the term popularized by the Numpy numerical environment in the Python programming language. In other programming languages and environments, broadcasting may also be known as <em>binary singleton expansion</em> (BSX, in <span class="sc">matlab</span>, and the origin of the name of the <code>bsxfun</code> function), <em>recycling</em> (R programming language), <em>single-instruction multiple data</em> (SIMD), or <em>replication</em>. <h4 class="subsection">19.2.1 Broadcasting and Legacy Code</h4> <p>The new broadcasting semantics almost never affect code that worked in previous versions of Octave. Consequently, all code inherited from <span class="sc">matlab</span> that worked in previous versions of Octave should still work without change in Octave. The only exception is code such as <pre class="example"> try c = a.*b; catch c = a.*a; end_try_catch </pre> <p class="noindent">that may have relied on matrices of different size producing an error. Due to how broadcasting changes semantics with older versions of Octave, by default Octave warns if a broadcasting operation is performed. To disable this warning, refer to its ID (see <a href="doc_002dwarning_005fids.html#doc_002dwarning_005fids">doc-warning_ids</a>): <pre class="example"> warning ("off", "Octave:broadcast"); </pre> <p class="noindent">If you want to recover the old behavior and produce an error, turn this warning into an error: <pre class="example"> warning ("error", "Octave:broadcast"); </pre> <p class="noindent">For broadcasting on scalars that worked in previous versions of Octave, this warning will not be emitted. </body></html>