Máté Wierdl
Máté Wierdl

Reputation: 133

gnuplot: how to sum over an arbitrary list

For gnuplot, I have a large list of (randomly generated) numbers which I want to use as indices in a sum. How do I do it?

Here is what I mean. Let's say the list of numbers is

list = [81, 37, 53, 22, 72, 74, 44, 46, 96, 27]

I have a function

f(x,n) = cos(n*x)

I now want to plot the function, on the interval (-pi,pi) which is the sum of the f(x,n) as n runs through the numbers in list.

Upvotes: 2

Views: 354

Answers (2)

theozh
theozh

Reputation: 25724

Here is an alternative suggestion. The macro in maij's answer could simply be replaced by gnuplot's sum function (check help sum). Just for illustration purpose, I've chosen a different function, different list and different range in order to show the approximation of sin(x).

enter image description here . . .

Script: (works for gnuplot>=4.6.0, March 2012)

### plot sum of function values
reset

list = "1 3 5 7 9 11 13"

f(x,n) = (-1)**int(n/2)*x**int(n)/int(n)!

mySum(x,N) = sum[j=1:N] f(x,word(list,j))

set xrange[-2*pi:2*pi]
set yrange[-2:2]
set samples 1000
set key top out

plot for [i=1:words(list)] mySum(x,i) w l ti sprintf("%d",i), \
     sin(x) w l lw 2 lc rgb "red"
### end of script

Result:

enter image description here

Upvotes: 1

maij
maij

Reputation: 4218

If you can control how your list looks like, try the following:

num = 10

# Let the numbers be in a space separated string. 
# We can access the individual numbers with the word(string, index) function.
list = "81 37 53 22 72 74 44 46 96 27"

f(x,n) = cos(n*x)

set terminal pngcairo
set output "sum_cos.png"

set xrange [-pi:pi]
set samples 1000

# Build the plot command as a macro.
plt_cmd = ""
do for [n=1:num] {
   plt_cmd = sprintf("%s + f(x,%s)", plt_cmd, word(list,n))
}

# Check what we have done so far.
print plt_cmd

titlestring = "{/Symbol S} cos(n_i*x), i = 1 ...".num

# Finally plot the sum by evaluating the macro.
plot @plt_cmd title titlestring

This is the result:

sum of cosine functions

Upvotes: 2

Related Questions