从文件中读取函数系数 [英] Read function coefficients from file

查看:52
本文介绍了从文件中读取函数系数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下文件:

1,2,3
4,5,6
7,8,9

我想用文件值作为系数,用gnu​​plot绘制3个多项式,形式为a x ^ 2 + b x + c.直接执行此操作,我会这样做:

I would like to have gnuplot plot 3 polynomials of the form ax^2 + bx +c, using the file values as coefficients. Performing this directly, I would do:

plot x**2+2*x+3, 4*x**2+5*x+6, 7*x**2+8*x+9

但是我想以编程方式对输入文件中的任意行进行此操作.

But I would like to do this programatically, for an arbitrary number of lines in the input file.

我想我可能会接近受此答案启发的代码:

I think I might be close with code inspired by this answer:

n= "`awk 'END {print NR}' < test.dat`"
i=0
while i<n{
f(a,b,c,x)=a*x**2+b*x+c
plot 'test.dat' every ::i::i using f($1,$2,$3,x)
}

但是此操作失败,并显示undefined variable: x

But this fails with undefined variable: x

推荐答案

多年来我一直遇到相同的问题,最后我设法找到了解决方案. 它需要创造性地使用stats函数将文件中的值分配给变量,并使用几个do for [...]循环将一些命令存储在临时文件中

I've had the same problem for ages and finally I managed to find a solution. It requires a creative use of the stats function to assign the values from the file to the variables and a couple of do for [...] loops to store some commands in a temp file

filename = "InputFileName.dat"
stats filename nooutput
nlines = STATS_records-1
set print "temp.gnuplot"
do for [i=0:nlines] {\
  print sprintf("stats filename every ::%i::%i using (a%i=$1,b%i=$2,c%i=$3,0):(0) nooutput",i,i,i,i,i)}
set print
load "temp.gnuplot"
set print "temp.gnuplot"
do for [i=1:nlines] {print sprintf("replot  a%i*x**2 + b%i*x + c%i",i,i,i)}
plot a0*x**2 + b0*x +c0
load "temp.gnuplot"
set print

根据需要更改filename变量.完成像! rm temp.gnuplot这样的系统调用后,就可以删除临时文件.

Change the filename variable as you need. You can remove the temp file once you are finished with a system call like this ! rm temp.gnuplot.

我知道这不是特别优雅,而且我特别不喜欢使用临时文件,如果有人知道如何执行一个字符串变量,我将很高兴知道.但是,嘿,它可以工作(甚至在Windows下也可以)!

I know is not particularly elegant and I especially don't like the use of a temp file, if somebody knows how to execute a string variable I'd be happy to know. But hey, it works (even under Windows)!

忘记了这些作为输入.

这篇关于从文件中读取函数系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆