1

I have several functions f1(x),f2(x)...fn(x). Each function is made to fit a data set called v(i) Each one has this form for example : f1(x)=a1*x Now i would like to plot all of them by calling a for loop

plot for [i=i0:ie:di] v(i) using 1:($3)

So far so good. Now i would like to call a1,a2,a3..etc for each i, for example to rescale the data, and i would write it like this

 plot for [i=i0:ie:di] v(i) using 1:($3/a(i))

where

a(i)=sprintf("a%01.0f",i)

The problem is to pass from a string to a float, and to gnuplot to recognize it as a defined parameter. I've tried to add zero to make the implicit cast but it doesn't work. Even if i print

print (a(i)+0)

Does someone has an idea to achieve getting my a(i) ?

Thanks you very much for any suggestion

Thanks you for the real function suggestion, but i still get the following problem, which can be seen as this minimal example

a1=12
a(x)=sprintf("a%01.0f",x)
print real(a(i)) #want to get 12 here
Non-numeric string found where a numeric expression was expected

2 Answers2

1

You need to use the value function (see help value). The value function accepts a string and returns the value of the variable whose name is that string.

For example

a1 = 2
a2 = 3
a3 = 1

plot for[i=1:3] x**value(sprintf("a%d",i)) t sprintf("a%d",i)

produces

enter image description here

Here, for each value of i, we built up the name of a variable with sprintf("a%d",i) which returns a1, a2, or a3 depending on the value of i. In order to get the value of the variable, we pass that string to the value function, which treats the string as the name of a variable and looks up the value. We see that the curve for a1 is x^2 (as a1 is 2), the curve for a2 is x^3 (as a2 is 3), and the curve for a3 is x (as a3 is 1).

In your case, you can just define your a(i) function as

a(i)=value(sprintf("a%01.0f",i))

and then a(1) will be the value of a1, a(2) will be the value of a2 and so on. With this change, your code will work exactly as written.

Matthew
  • 7,440
  • 1
  • 24
  • 49
-1

To convert a string to a float, you have the real function:

my_val=2.3
my_str=sprintf("%f",my_val)
print my_str # this is a string
print real(my_str) # this is a float

from help real:

The real(x) function returns the real part of its argument.

if x is a string function (i.e. function which returns the name of a variable) you need to use on it the value function:

a1=12
a(x)=sprintf("a%01.0f",x)
print real(value(a(1)))

p.s. you also have the int function which does the same with integers

Otherwise, in case you need to store an array (which gnuplot isn't capable of) you might want to look at this suggestion: https://stackoverflow.com/a/35729052/2743307

Community
  • 1
  • 1
bibi
  • 3,671
  • 5
  • 34
  • 50