# Using \foreach to generate functions

I wish to plot a function based on collection of simple functions. For instance, the maximum of some functions:

\begin{tikzpicture}[]
\begin{axis}
{
max( 2*x, 3*x, 4*x, 5*x, 0)
};
\end{axis}
\end{tikzpicture}


How can I generate this function using \foreach?

The following doesn't seem to work

\begin{tikzpicture}[]
\begin{axis}
{
max(
\foreach \k in {2,3,4,5}
{\k*x, }
0)
};
\end{axis}
\end{tikzpicture}


as it gives the following error:

! Undefined control sequence.
\foreach ...@empty \let \pgffor@assign@after@code
=\pgfutil@empty \let \pgff...
l.164       };

• Why not determine the max symbolically? For example, the maximum of the functions you've listed will always be 5x when x>0 or 0 when x<0, so you can just use max(5x, 0). – David Z Jun 15 '14 at 2:43
• I gave 2*x etc only as a simple example. The real functions I have are more complicated, and their maximum changes with x, yet all have a similar form. A better example would probably be sin(\k *x). – Ran G. Jun 15 '14 at 2:52
• Yes, but my point is, whatever your actual functions are, consider finding their maximum symbolically. You can construct a piecewise function with ifthenelse. As far as I know, you can't use \foreach in a mathematical expression, so I'd suspect it's impossible to do what you want to do without implementing your function in TeX. – David Z Jun 15 '14 at 2:55
• First, to do these sorts of calculations, you need to use \pgfmathparse etc. (Note, (x,y,z) coordinates are automatically run through \pgfmathparse). – John Kormylo Jun 15 '14 at 2:55
• If I understand correctly, you want to have parametrised familly of functions ? A solution may have your convinence here : tex.stackexchange.com/questions/184944/… – Tarass Jun 15 '14 at 11:12 \documentclass[tikz]{standalone}
\usepackage{pgfplots}
\usetikzlibrary{calc}
\pgfplotsset{compat=1.9}
\begin{document}

\begin{tikzpicture}[
declare function={
f1(\t)  = 5-5*\t ;
f2(\t)  = 4-2*\t ;
f3(\t)  = 3-\t ;
f4(\t)  = 2-.5*\t ;
f5(\t)  = e^(\t-4) ;
Max(\t) = max(  {f1(\t)},
{f2(\t)},
{f3(\t)},
{f4(\t)},
{f5(\t)}
%                   {f6(\t)},
%                   {f7(\t)},
%                   {f8(\t)},
%                   {f9(\t)},
) ;
}
]

\begin{axis}[xmin=0,xmax=5,ymax=7]
{
Max(x)
};
\end{axis}
\end{tikzpicture}
\end{document}


Whit egreg answer here : 's \expandafter, \expandbefor : what else? : \begin{document}
\Liste{\n-\n/(6-\n)*x}{5}

\bigskip

\begin{tikzpicture}

\begin{axis}[xmin=0,xmax=5,samples=400]
\Liste[\foo]{\n-\n/(6-\n)*x}{5}

• Thanks, this seems to be in the right direction. I'll try to understand the \expandafter, \expandbefore commands – Ran G. Jun 15 '14 at 17:36