【问题标题】:gnuplot linear fit within for loopgnuplot 线性拟合 for 循环
【发布时间】:2014-06-23 13:25:33
【问题描述】:

我有一个脚本可以正确绘制 100 个单独的数据文件。现在我想做一个线性 for 循环中每个图的拟合。但是,当我的脚本到达 fit 命令并显示消息“跳过不可读的文件“f(x) = a100*x + b%d”时,我的脚本崩溃了。任何人都可以提供正确的语法吗?谢谢你。

plotfile = "graph.eps"
set output plotfile
n=100
filename(n) = sprintf("%d_mod.int", n)
fstr(n) = sprintf('f(x) = a%d*x + b%d ' , n)
plot for [i = 1:n] filename(i) u 1:2 title sprintf("%d", i) w lp
fit for  [i = 1:n] fstr(i) filename(i) u 1:2 via a, b

【问题讨论】:

    标签: gnuplot


    【解决方案1】:

    fit 不支持迭代。这是你可以做到的,但它需要一些摆弄;)

    # 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)
    

    如果我使用以下两个测试文件,这对我来说很好:

    文件file1.dat

    1 1
    2 2.1
    3 3
    

    file2.dat:

    1 1.5
    2 2.7
    3 4
    

    4.6.5的结果是:

    要使拟合的实际结果显示在键中,您必须构造绘图字符串plotstr,如下所示:

    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) ? "" : ", ")
    }
    

    结果

    【讨论】:

    • 这对我来说非常有效(也使用版本 4.6.5)。我只需要更改我的文件名——正是我要找的——非常感谢!
    • 我可以再问一个问题吗?如何更改绘图字符串,以便绘制整个拟合函数 f1(x) =a1*x + b1 而不仅仅是 f1(x)?如果我将当前表达式扩展为“f%d(x) = a%d*x + b%d”,则会收到错误消息“f_sprintf:尝试以数字格式打印字符串值”
    • f1(x) 是绘制的整个拟合函数。或者您想将f1(x) = a1*x + b1 放在图例中(甚至可能将a1b1 替换为实际数字)?
    • 抱歉不准确 :( 是的,我的意思是如何在图例中打印整个拟合函数(a1 和 b1 的实际数字)?我还在学习语法规则.. .
    • 您的评论不完整。请注意,do for ... { plot ...plot for ... 不同,请参见例如loop over array in gnuplot.
    猜你喜欢
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多