How to make "sigma" summation of a function by i variable in GNU Octave?

5.6k Views Asked by At

I need to make summation using function of a variable i like this:

\begin{equation} \sum_{i=1}^5\left(|x_{i}| - |37-x_i|\right) \end{equation}

In Maxima it is done like this (ar - array of $x_1$...$x_i$ values):

ar:[1,2,3,4,5];
sum(ar[i]-abs(37-ar[i]), i, 1,5);

Besides, Maxima allows even specifying infinite upper limit for summation (just write inf or infinity if I remember correctly).

But I cannot find anything similar in GNU Octave - its sum() and symsum() seem to accept and summate only matrix/vector, but not a function.

1

There are 1 best solutions below

0
On BEST ANSWER

First, suppose a vector $x$ is given, e.g. by

x = [2 3 5 7 11]

Then the following computes the sum:

sum(arrayfun(@(k) abs(x(k)) - abs(37 - x(k)), 1:5))

Explanation

  1. 1:5 create a vector from $1$ to $5$
  2. @(k) abs(x(k)) - abs(37 - x(k)) create an anonymous function with one free variable $k$, such that when given $k$, computes $|x_k| - |37 - x_k|$
  3. arrayfun(@(k) abs(x(k)) - abs(37 - x(k)), 1:5) applies the anonymous function pointwisely to each element in the vector, so it is the same as map in most functional programming language
  4. sum adds up everything in the vector

Abstraction

In fact we can define the $\sum$ notation for finite sum by sigma = @(f, a, b) sum(arrayfun(f, a:b)). Then we can write the sum more succinctly as sigma(@(k) abs(x(k)) - abs(37 - x(k)), 1, 5).

Feel free to ask if something is not clear.