How to define and access array in GNUplot?

If you are using Gnuplot 5.1 or superior and need a 1-d array, you simply define the array with size N, remembering that the indices go from 1 to N:

gnuplot> array A[3] #Array definition
gnuplot> A[1]=2
gnuplot> A[3]=4
gnuplot> print A[1]
2
gnuplot> print A    #Print the array, with empty A[2]
[2,,4]

If you need more than one dimension or are using previous versions of Gnuplot, you can do the following:

Since there are no vector variables in previous versions of Gnuplot, two functions can be defined to get and set values to a behind the scenes variable whose name include the index. The functions are:

aGet(name, i) = value(sprintf("_%s_%i", name, i)) 
aSet(name, i, value) = sprintf("_%s_%i = %.16e", name, i, value)

To assign and retrieve values on the array A you do

eval aSet("A",2,3)
print aGet("A",2)

What these functions do is to access a variable called _A_2.

You can build similar function to work with matrices:

mGet(name, i, j) = value(sprintf("_%s_%i_%i", name, i, j)) 
mSet(name, i, j, value) = sprintf("_%s_%i_%i = %.16e", name, i, j, value) 

Leave a Comment