How to define and access array in GNUplot?

fronthem picture fronthem · Jun 10, 2015 · Viewed 17k times · Source

This is rather easy question or maybe too easy question. But i tried to find the way to done these already and could not find even in GNUplot document. Might be my mistake or misunderstood something about array concept in GNUplot. My question is How to define and access array in GNUplot?

Please just provide easy example of array declaration, assign value of array over loop. i think that's enough and i think this will be useful for other people too.

Answer

bmello picture bmello · Mar 1, 2016

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)