8

I'm trying to use user-defined math functions with pgf to make a plot. The plot will consist of several straight lines given by a function of three arguments. (I know there are easier ways to do this, but I need to annotate the plot quite extensively, for which TikZ will be great.) The MWE below illustrates what I'm trying to do:

\documentclass[10pt]{article}

\usepackage{tikz}
\usepackage[active,tightpage]{preview}
\PreviewEnvironment{tikzpicture}

\pgfmathdeclarefunction{r51}{3}{%
  \pgfmathsetmacro{gterm}{(#1+1.0)/(2.0*#1)}%
  \pgfmathsetmacro{denom}{1.0+gterm*(#2-1.0)}%
  \pgfmathparse{(1.0+0.5*(#2-1.0))*#3/denom+((#2-1.0)/(2.0*#1)/denom)}%
}

\newcommand{\drawline}[4]{
  \draw (#3,r51(#1,#2,#3))--(#4,r51(#1,#2,#4));     
}  

\begin{document}
  \thispagestyle{empty}
  \begin{tikzpicture}
% axis limits
  \def\xamin{- 0.25}
  \def\yamin{- 0.25}
  \def\xamax{  8.25}
  \def\yamax{  7.25}
% draw grid  
  \draw[very thin,color=gray] (\xamin,\yamin) grid (\xamax,\yamax); 
% draw axes 
  \draw[->] (\xamin,0.0) -- (\xamax,0.0) node[right] {$x$};
  \draw[->] (0.0,\yamin) -- (0.0,\yamax) node[above] {$y$};
% draw first line
  \drawline{1.4}{1.5}{0.1}{1.67} 
  \end{tikzpicture}
\end{document}

When I run it, I get the following error:

! Missing control sequence inserted.
<inserted text> 
                \inaccessible 
l.31     \drawline{1.4}{1.5}{0.1}{1.67}

I'm sure this is quite a basic question, but I have not been able to find any other examples that would have given me a clue as to how to fix it. Thanks for any help.

2

1 Answer 1

9

Your code works for me with just some little changes:

  1. instead of gterm and denom use \gterm and \denom.
  2. use { and } to protect r51(a,b,c) in \drawline definition.

If I've understood your definition of r51, it's easier to obtain a simple form. I've called it r52. They look the same.

\documentclass{standalone}

\usepackage{tikz}

\pgfmathdeclarefunction{r51}{3}{%
  \pgfmathsetmacro{\gterm}{(#1+1.0)/(2.0*#1)}%
  \pgfmathsetmacro{\denom}{1.0+\gterm*(#2-1.0)}%
  \pgfmathparse{(1.0+0.5*(#2-1.0))*#3/\denom+((#2-1.0)/(2.0*#1)/\denom)}%
}

\newcommand{\drawline}[4]{
  \draw (#3,{r51(#1,#2,#3)})--(#4,{r51(#1,#2,#4)});     
}  

\pgfmathdeclarefunction{r52}{3}{%
  \pgfmathparse{(#1*#2*#3+#1*#3+#2-1.0)/(#1+#1*#2+#2-1.0)}%
}

\begin{document}
  \thispagestyle{empty}
  \begin{tikzpicture}
% axis limits
  \def\xamin{- 0.25}
  \def\yamin{- 0.25}
  \def\xamax{  8.25}
  \def\yamax{  7.25}
% draw grid  
  \draw[very thin,color=gray] (\xamin,\yamin) grid (\xamax,\yamax); 
% draw axes 
  \draw[->] (\xamin,0.0) -- (\xamax,0.0) node[right] {$x$};
  \draw[->] (0.0,\yamin) -- (0.0,\yamax) node[above] {$y$};
% draw first line
  \drawline{1.4}{1.5}{0.1}{1.67} 
  \draw[red] (0.1,{r52(1.4,1.5,0.1)})--(1.67,{r52(1.4,1.5,1.67)});     
  \end{tikzpicture}
\end{document}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .