fit
doesn't support iterations. Here is how you can do it, but it needs some fiddling ;)
# define the functions depending on the current number
fstr(N) = sprintf("f%d(x) = a%d*x + b%d", N, N, N)
# The fitting string for a specific file and the related function
fitstr(N) = sprintf("fit f%d(x) 'file%d.dat' via a%d,b%d", N, N, N, N)
n = 2
# Do all the fits
do for [i=1:n] {
eval(fstr(i))
eval(fitstr(i))
}
# construct the complete plotting string
plotstr = "plot "
do for [i=1:n] {
plotstr = plotstr . sprintf("f%d(x), 'file%d.dat'%s ", i, i, (i == n) ? "" : ", ")
}
eval(plotstr)
This works fine for me, if I use the following two test files:
File file1.dat
:
1 1
2 2.1
3 3
and file2.dat
:
1 1.5
2 2.7
3 4
The result with 4.6.5 is:
To have the actual result of the fitting displayed in the key you must construct the plotting string plotstr
as follows:
plotstr = "plot "
do for [i=1:n] {
t = sprintf("f%d(x) = %.2f*x + %.2f", i, value(sprintf('a%d', i)), value(sprintf('b%d', i)))
plotstr = plotstr . sprintf("f%d(x) lt %d t '%s', ", i, i, t).
sprintf(" 'file%d.dat' lt %d %s ", i, i, (i == n) ? "" : ", ")
}
with the result
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…