6

I defined a macro that gets as input a string like sin(x)+3, a starting x and an ending x, which is plotted using \addplot from PGFplots.

Now I want to evaluate this function for x equal to the ending x provided to the macro as an argument, to find out at what height the function ends.

The problem is: how to evaluate a string like sin(x)+3 with x given?

I tried to use pgfmathparse but failed, and I know there are solutions with \x instead, but I want to use only the string sin(x)+3.

EDIT: Ok this is my code so far:

\renewcommand\line[2]{\addplot[domain=#1]{#2};}
\newcommand\dotted[2]{\addplot[dotted] plot[] coordinates{(#1)(#2)};\addplot[holdot] coordinates{(#1)};\addplot[holdot] coordinates{(#2)};}

\newcommand\pwpreviousset{0}
\newcommand\pwpreviousx{0}
\newcommand\pwpreviousy{0}
\newcommand\pwstart[1]{\renewcommand\pwpreviousset{0}\renewcommand{\pwpreviousx}{#1}}
\newcommand\pw[4]
{
\ifnum\pwpreviousset=1
    \dotted{{\pwpreviousx,\pwpreviousy}}{{\pwpreviousx,#1}}
\fi
\line{\pwpreviousx:#4}{#2}
\renewcommand{\pwpreviousx}{#4}
\renewcommand{\pwpreviousy}{#3}
\renewcommand\pwpreviousset{1}
}

The code above works perfectly, only i want arguments 1 and 3 of macro pw to be automaticly determined. These arguments represent the starting and ending y value of the function that is argument 2. I use them like this:

\pwstart{0}
\pw{1}{1+x}{4}{3}
\pw{-1}{2-x}{-2}{4}

But I want to determine the starting y and ending y programmaticly.

1
  • 1
    Please post your code, it is almost impossible to help without seeing what you have done until now
    – Red
    Commented Nov 4, 2013 at 12:35

1 Answer 1

9

To do this, you need to define x to be a function, using

\pgfkeys{/pgf/declare function={x=90;}}

Then you can use your expression in \pgfmathparse:

\documentclass{article}
\usepackage{tikz}
\begin{document}
\pgfkeys{/pgf/declare function={x=90;}}
\pgfmathparse{sin(x)+3}\pgfmathresult
\end{document}
2
  • Is it also possible to "undeclare" the function afterwards? Because I'm getting errors like "The function x already exists." if I try to use your solution for different x.
    – Carucel
    Commented Nov 4, 2013 at 12:48
  • You can keep the definition of x local by enclosing the relevant part in {...}.
    – Jake
    Commented Nov 4, 2013 at 12:50

You must log in to answer this question.

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