Next: Nesting and Fixed Points, Previous: Mapping, Up: Reducing and Mapping

#### 10.8.3 Reducing

The `V R` (`calc-reduce`) [`reduce`] command applies a given binary operator across all the elements of a vector. A binary operator is a function such as `+` or `max` which takes two arguments. For example, reducing `+` over a vector computes the sum of the elements of the vector. Reducing `-` computes the first element minus each of the remaining elements. Reducing `max` computes the maximum element and so on. In general, reducing `f` over the vector ‘`[a, b, c, d]`’ produces ‘`f(f(f(a, b), c), d)`’.

The `I V R` [`rreduce`] command is similar to `V R` except that works from right to left through the vector. For example, plain `V R -` on the vector ‘`[a, b, c, d]`’ produces ‘`a - b - c - d`’ but `I V R -` on the same vector produces ‘`a - (b - (c - d))`’, or ‘`a - b + c - d`’. This “alternating sum” occurs frequently in power series expansions.

The `V U` (`calc-accumulate`) [`accum`] command does an accumulation operation. Here Calc does the corresponding reduction operation, but instead of producing only the final result, it produces a vector of all the intermediate results. Accumulating `+` over the vector ‘`[a, b, c, d]`’ produces the vector ‘`[a, a + b, a + b + c, a + b + c + d]`’.

The `I V U` [`raccum`] command does a right-to-left accumulation. For example, `I V U -` on the vector ‘`[a, b, c, d]`’ produces the vector ‘`[a - b + c - d, b - c + d, c - d, d]`’.

As for `V M`, `V R` normally reduces a matrix elementwise. For example, given the matrix ‘`[[a, b, c], [d, e, f]]`’, `V R +` will compute ‘`a + b + c + d + e + f`’. You can type `V R _` or `V R :` to modify this behavior. The `V R _` [`reducea`] command reduces “across” the matrix; it reduces each row of the matrix as a vector, then collects the results. Thus `V R _ +` of this matrix would produce ‘`[a + b + c, d + e + f]`’. Similarly, `V R :` [`reduced`] reduces down; `V R : +` would produce ‘`[a + d, b + e, c + f]`’.

There is a third “by rows” mode for reduction that is occasionally useful; `V R =` [`reducer`] simply reduces the operator over the rows of the matrix themselves. Thus `V R = +` on the above matrix would get the same result as `V R : +`, since adding two row vectors is equivalent to adding their elements. But `V R = *` would multiply the two rows (to get a single number, their dot product), while `V R : *` would produce a vector of the products of the columns.

These three matrix reduction modes work with `V R` and `I V R`, but they are not currently supported with `V U` or `I V U`.

The obsolete reduce-by-columns function, `reducec`, is still supported but there is no way to get it through the `V R` command.

The commands `C-x * :` and `C-x * _` are equivalent to typing `C-x * r` to grab a rectangle of data into Calc, and then typing `V R : +` or `V R _ +`, respectively, to sum the columns or rows of the matrix. See Grabbing From Buffers.