McLeary
McLeary

Reputation: 1281

Gnuplot for loop with increment smaller then 1

I was trying to plot the following

plot for [h=0:2:0.1] sin(h*x)

But it gives the following error

gnuplot> plot for [h=0:2:0.1] sin(x*h)
                     ^
         Expecting iterator     for [<var> = <start> : <end> {: <incr>}]
         or for [<var> in "string of words"]

But the following line works just fine

plot for [h=0:2:1.1] sin(x*h)

Is this a bug or it is supposed to work this way? I mean, why it is not accepting increments smaller than 1?

I'm using the following version of gnuplot

G N U P L O T
Version 5.0 patchlevel 1    last modified 2015-06-07 

Upvotes: 6

Views: 5830

Answers (2)

Miguel
Miguel

Reputation: 7627

In addition to Christoph's answer, another way to do arbitrary increment loops without the need to do the scaling within the function is to define a list of values that contains all the elements to loop through. This can easily be done with a system call to seq:

list(start,end,increment)=system(sprintf("seq %g %g %g", start, increment, end))
plot for [i in list(0.,1.,0.1)] sin(i*x)

enter image description here

An equivalent gnuplot-only solution (proposed by Karl in the comments) that will work also if seq is not available is the following:

start=0.; end=1.; inc=0.1
list = ""; a=start-inc; while (a<end) {list=list.sprintf(" %.3f",a=a+inc)}
plot for [i in list] sin(i*x)

Note that while loops are only available since gnuplot 4.6.

Upvotes: 3

Christoph
Christoph

Reputation: 48390

Gnuplot supports iterations only with integer values (see documentation section "For loops in plot command", p 98). Values smaller then 1 are casted as integer to 0, which is not allowed. Using e.g.

plot for [h=0:3:1.5] sin(x*h) title sprintf('%.1f', h)

plots four curves with h having the values 0, 1, 2, 3. To use smaller values you must scale the iteration value later:

plot for [h=0:20:1] sin(0.1*h*x)

Upvotes: 7

Related Questions