2

I am using gnuplot 5.2.4.

I am doing a for-loop, to analyse in each cycle a different column (or combination of columns) of a file. The column to be used is written in an array and is passed to the commands as a macro.
The code is written in a .plt file that I load in gnuplot. It looks like this (here for example I'm using the 1.dat file in the \gnuplot\demo) :

set macros 

array label[2]

label[1]="First_Cycle"
label[2]="Second_Cycle"

array index[2]

index[1]="(column(2))"
index[2]="(column(2)-column(1))"

fileDat = "1.dat"


 do for [k = 1 : 2] {

         fileExport = sprintf("%s.gif",label[k])    
         print fileExport 

         set term gif size  1920,1280 enhanced
         set output fileExport 

         indexk = index[k] 
         print k," ",index[k]," ", indexk
         stats  fileDat u @indexk name "DV" #noout 
         plot  fileDat u @indexk ti label[k] 
  }

indexk is printed correctly at each cycle, however, I obtain the following warning: warning: indexk is not a string variable and the commands stats and plot analise always the column in index[1] at each cycle.

However, if I comment the do for loop and increase the k by hand, the code works correctly, no warning, no problem, like this:

set macros 

array label[2]

label[1]="First_Cycle"
label[2]="Second_Cycle"

array index[2]

index[1]="(column(2))"
index[2]="(column(2)-column(1))"

fileDat = "1.dat"

k=2

 #do for [k = 1 : 2] {

         fileExport = sprintf("%s.gif",label[k])    
         print fileExport 

         set term gif size  1920,1280 enhanced
         set output fileExport 

         indexk = index[k] 
         print k," ",index[k]," ", indexk
         stats  fileDat u @indexk name "DV" #noout 
         plot  fileDat u @indexk ti label[k] 
  #}
BaBuZ87
  • 23
  • 2

1 Answers1

1

You can think of gnuplot macros (@ + string variable name) as roughly equivalent to C language preprocessor directives. They describe a substitution that is performed only once, the first time the line of code is encountered. So trying to change one inside a loop will not work.

In some contexts the gnuplot directive "evaluate( )" is equivalent to dynamic macro substitution, but in the case shown you need an expression rather than a statement. So something like:

Col(k) = (k == 1) ? column(2) : column(2) - column(1)

do for [k=1:2] {
    ...
    stats fileDat using Col(k) name "DV"
    plot fileDat using Col(k) ti label[k]
}
Ethan
  • 13,715
  • 2
  • 12
  • 21
  • Very thank you for the suggestion. Hence, I'll use something like this for all the cicles I need: Col(k) = (k == 1) ? column(2) : (k==2) ? column(2) - column(1) : (k==3) ? ...... : (k==4) ? : etc etc :1/0 stats fileDat u (Col(k)) name "DV" – BaBuZ87 Aug 10 '18 at 12:57