Applying and doing math on two functions read from a file using pgf
There is some expansion stuff going on (which I don't understand so won't attempt to explain it). But, here is one way to achieve the desired results:
Code:
\begin{filecontents}{data.dat}
f(x) g(x)
x x+1
\end{filecontents}
\documentclass{article}
\usepackage{xstring,pgfplotstable,filecontents}
\begin{document}
\newcommand{\getfx}[1]{
\pgfplotstablegetelem{#1}{f(x)}\of{data.dat}
}
\newcommand{\getgx}[1]{
\pgfplotstablegetelem{#1}{g(x)}\of{data.dat}
}
\def\SetFeightValue{%
\getfx{0}%
\StrSubstitute[0]{\pgfplotsretval}{x}{8}[\feightValue]%
}
\def\SetGeightValue{%
\getgx{0}%
\StrSubstitute[0]{\pgfplotsretval}{x}{8}[\geightValue]%
}
\SetFeightValue
\SetGeightValue
\pgfmathsetmacro{\MyResults}{(\feightValue)/(\geightValue)}
(\feightValue)/(\geightValue)=\MyResults
\end{document}
Edit
You can do this without xstring
if you have the input slightly modified. The previous code fails because pgfmath
does not like \x{}
. So I simply change it to (\x)
. (You cannot leave \x
along because otherwise pgfplotstable
will not see the space between \x
and \x+1
.)
\documentclass{article}
\usepackage{pgfplotstable,filecontents}
\begin{filecontents}{data.dat}
f(\x) g(\x) h(\x)
(\x) \x+1 f(\x)/g(\x)
\end{filecontents}
\begin{document}
{
\def\x{variable x}
\def\DeclareFunctionFromTable#1{
\pgfplotstablegetelem{0}{#1}\of{data.dat}
\expandafter\DeclareFunctionFromTableAux\expandafter{\pgfplotsretval}{#1}
}
\def\DeclareFunctionFromTableAux#1#2{\tikzset{declare function={#2=#1;}}}
\DeclareFunctionFromTable{f(\x)}
\DeclareFunctionFromTable{g(\x)}
\DeclareFunctionFromTable{h(\x)}
\begin{tikzpicture}
\begin{axis}
\addplot(\x,{f(\x)});
\addplot(\x,{g(\x)});
\addplot(\x,{h(\x)});
\end{axis}
\end{tikzpicture}
\end{document}
You can do this without xstring
if you have the input slightly modified.
\documentclass{article}
\usepackage{pgfplotstable,filecontents}
\begin{filecontents}{data.dat}
f(\x) g(\x) h(\x)
\x{} \x+1 f(\x)/g(\x)
\end{filecontents}
\begin{document}
\def\x{x}
\def\DeclareFunctionFromTable#1{
\pgfplotstablegetelem{0}{#1}\of{data.dat}
\expandafter\DeclareFunctionFromTableAux\expandafter{\pgfplotsretval}{#1}
}
\def\DeclareFunctionFromTableAux#1#2{\pgfkeys{/pgf/declare function={#2=#1;}}}
\DeclareFunctionFromTable{f(\x)}
\DeclareFunctionFromTable{g(\x)}
\DeclareFunctionFromTable{h(\x)}
\pgfmathparse{h(8)}
\pgfmathresult
\end{document}