3

I use Gnuplot and I would like to save values of a datafile into a variable with condition. For example, I have the following datafile 'example.dat':

columnl   column2
   5        7.0
   3        4.0
   7        6.0

In my gnuplot script, I would like to be able to write:

variable = " in the file 'example.dat' ($1)==5 ? $2 : 1/0 "

which would be here the same as:

variable = 7.0

of course the value depends on the datafile.

So is it possible?

If not, is it possible without condition?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • probably one answer from here helps: http://stackoverflow.com/questions/7540614/reading-dataset-value-into-a-gnuplot-variable-start-of-x-series?rq=1 – Tony J Stark Jan 23 '14 at 14:57
  • 3
    You could use `stats 'example.dat' using ($1 == 5 ? $2 : 0); variable = STATS_sum`, but that requires, that the value you want to extract is uniquely defined, i.e. there is exactly one row which matches the condition. – Christoph Jan 23 '14 at 20:21

2 Answers2

0

This is how I worked around the problem:

A=""
plot file u (A=A.sprintf(' %g',$2), $1):2

All the entries from column 2 will be written to A, which you can access then via:

word(A,i)

where i is the number of the raw (starting at 1) words(A) gives you the total length.

Alex
  • 1
  • 1
0

Just for the records, you can workaround the limitation of Christoph's solution which allows only one occurrence of your check value in your data.

Two versions which return the corresponding value:

  1. for the first occurrence of your check value
  2. for the last occurrence of your check value

The example below works for gnuplot >=5.0.0, but if you use a file instead of the datablock $Data it will also work for gnuplot 4.6.0 (version at the time of OP's question).

Code:

### extract values via condition
reset

$Data <<EOD
  5   7.0
  3   4.0
  7   6.0
  5   1.0
  4   2.0
  5   3.0
  2   1.0
EOD

check = 5   # value to check

v=NaN
stats $Data u ($1==check ? v==v ? NaN : v=$2 : 0) nooutput
print sprintf("Value for first occurrence of %g: %g",check,v)

v=NaN
stats $Data u ($1==check ? v=$2 : 0) nooutput
print sprintf("Value for last occurrence of %g:  %g",check,v)
### end of code

Result:

Value for first occurrence of 5: 7
Value for last occurrence of 5:  3
theozh
  • 22,244
  • 5
  • 28
  • 72