Search code examples
rangegnuplot

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.


Solution

  • 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