Nister
Nister

Reputation: 226

Gnuplot: Plotting different functions in a loop

I'd like to plot the Hermite polynomials in the same graph without having to type them one by one using a loop. I've tried something like this:

    H0(x) = 1 
    H1(x) = 2*x 
    H2(x) = 4*x*x-2 
    H3(x) = 8*x**3-12*x 
    H4(x) = 16*x**4-48*x**2+12 
    H5(x) = 32*x**5-160*x**3+120*x

    plot for[i=0:5] H.i(x)

but It won't work, it'll say: undefined variable: H. I've seen the variable i can be used as a string but I haven't been able to find if there's a way to use it as a string when calling a function.

Upvotes: 1

Views: 676

Answers (2)

An improvement can be

set term wxt persist

set xrange[-1:1]

H(i,x) = (i == 0 ? 1 : \
      i == 1 ? 2*x : \
      i == 2 ? 4*x*x-2 : \
      i == 3 ? 8*x**3-12*x : \
      i == 4 ? 16*x**4-48*x**2+12 : \
      i == 5 ? 32*x**5-160*x**3+120*x : 1/0)

plot for[i=0:5] H(i,x) title sprintf("H(").sprintf('%d',i).sprintf(",x)")

Hermite

enter image description here

Upvotes: 0

Miguel
Miguel

Reputation: 7627

Try a different approach, including the index i as an argument of the function:

H(i,x) = (i == 0 ? 1 : \
          i == 1 ? 2*x : \
          i == 2 ? 4*x*x-2 : \
          i == 3 ? 8*x**3-12*x : \
          i == 4 ? 16*x**4-48*x**2+12 : \
          i == 5 ? 32*x**5-160*x**3+120*x : 1/0)

plot for[i=0:5] H(i,x)

enter image description here

Upvotes: 3

Related Questions