1

Let's say that I've got data called 'myData.dat' in the form

x  y
0  0
1  1
2  2
4  3
8  4
16 5

I need to find the following things from this data:

  • slope for points
    • 0 to 5
    • 1 to 5
    • 2 to 5
    • 3 to 5
    • 4 to 5
  • y-intercept for the same pairs
  • equation for the line connecting the same pairs

Then I need to plot the the data and overlay the lines; below is a picture of what I'm asking for.

enter image description here

I know how to obtain the the slope and y-intercept for a single pair of points, and plot the data and the equation of the line. For example for points 1 and 5:

set table
plot "myData.dat" using 0:($0==0 ? y1=$2 : $2)
plot "myData.dat" using 0:($0==4 ? y5=$2 : $2)
unset table

m1 = (y5 - y1)/(5-1)
b1 = y1 - m1*1
y1(x) = m1*x + b1 

I'm new to iteration (and gnuplot) and I think there's something wrong with my syntax. I've tried a number of things and they haven't worked. My best guess is that it would be in the form

plot for [i=1:4] using 0:($0==1 ? y.i=$1 : $1)

do for [i=1:5]{
m.i = (y5 - y.i)/(5-i)
b.i = y.i - m.i*1
y.i(x) = m.i*x + b.i    
}

set multiplot
plot "myData.dat" w lp
plot for [i=1:4] y.1(x)
unset multiplot

So what is going wrong? Is gnuplot able to concatencate the loop counter to variables?

  • Gnuplot's scripting abilities are rather limited; it's a plotting program. To do your stuff you would probably be better off using an different scripting language which generates the function strings for the equations which you can then `load`. – Christoph Nov 02 '14 at 10:11

1 Answers1

1

Your syntax is incorrect. Although there are other ways to do what you want, for instace using word(var,i), the most straightforward fix to what you already have would be to use eval to evaluate a string to which you can concatenate variables:

do for [i=1:5]{
eval "m".i." = (y5 - y".i.")/(5-".i.")"
eval "b".i." = y".i." - m".i."*1"
eval "y".i."(x) = m".i."*x + b".i    
}
Miguel
  • 7,497
  • 2
  • 27
  • 46
  • This works great for obtaining the equation for each pair of points. As for using the 'plot' function to iterate, I haven't quite figured that one out yet... but like Christoph commented above, gnuplot is quite limited in that regard, so I think I'll attack it from a different angle. – chocolate.broccoli Nov 07 '14 at 05:47
  • @chocolate.broccoli I answered to something similar today and remebered your case. Here is how you use`word()` to create arrays and access values within a loop: http://stackoverflow.com/a/26819987/1792075 – Miguel Nov 09 '14 at 00:38