Credits Overview Plotting Styles Commands Terminals

User-defined variables and functions

New user-defined variables and functions of one through twelve variables may be declared and used anywhere, including on the plot command itself.

User-defined function syntax:

      <func-name>( <dummy1> {,<dummy2>} ... {,<dummy12>} ) = <expression>

where <expression> is defined in terms of <dummy1> through <dummy12>. This form of function definition is limited to a single line. More complicated multi-line functions can be defined using the function block mechanism (new in this version). See function blocks.

User-defined variable syntax:

      <variable-name> = <constant-expression>

Examples:

      w = 2
      q = floor(tan(pi/2 - 0.1))
      f(x) = sin(w*x)
      sinc(x) = sin(pi*x)/(pi*x)
      delta(t) = (t == 0)
      ramp(t) = (t > 0) ? t : 0
      min(a,b) = (a < b) ? a : b
      comb(n,k) = n!/(k!*(n-k)!)
      len3d(x,y,z) = sqrt(x*x+y*y+z*z)
      plot f(x) = sin(x*a), a = 0.2, f(x), a = 0.4, f(x)
      file = "mydata.inp"
      file(n) = sprintf("run_%d.dat",n)

The final two examples illustrate a user-defined string variable and a user-defined string function.

Note that the variables pi (3.14159...) and NaN (IEEE "Not a Number") are already defined. You can redefine these to something else if you really need to. The original values can be recovered by setting:

      NaN = GPVAL_NaN
      pi  = GPVAL_pi

Other variables may be defined under various gnuplot operations like mousing in interactive terminals or fitting; see gnuplot-defined variables for details.

You can check for existence of a given variable V by the exists("V") expression. For example

      a = 10
      if (exists("a")) print "a is defined"
      if (!exists("b")) print "b is not defined"

Valid names are the same as in most programming languages: they must begin with a letter, but subsequent characters may be letters, digits, or "_".

Each function definition is made available as a special string-valued variable with the prefix 'GPFUN_'.

Example:

      set label GPFUN_sinc at graph .05,.95

See show functions, functions, gnuplot-defined variables, macros, value.