# Defining a macro with if statements [duplicate]

Possible Duplicate:
Piecewise defined function in tikz or tkz-fct

I wish to write a macro that gets a number x. If x is smaller than 1, it should return x, otherwise, it returns x^2. I need it for a piece-wise function for TikZ, but I want it as a macro as I will be running it several times. Any easy way to do it?

-

## marked as duplicate by Andrew Swann, Thorsten, Stefan Kottwitz♦Dec 29 '12 at 17:11

Welcome to TeX.sx!. Does this question on piecewise smooth functions in tikz solve your problem? – Andrew Swann Dec 29 '12 at 16:32
Thanks! Indeed I didn't know a simple command such as ifthenelse existed. That works great. – George Dec 29 '12 at 16:43

Use pgfmathparse

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{mindmap}

\newcommand*{\mycommand}[1]{%
\pgfmathparse{
ifthenelse(#1 < 1,#1,#1*#1)}
\pgfmathresult
}%
\begin{document}
Less than 1 (x = 0.5)\\
f(x) = \mycommand{0.5}

Equal to 1 (x = 1)\\
f(x) = \mycommand{1}

Greater than 1 (x = 2)\\
f(x) = \mycommand{2}
\end{document}


Which yields the following output:

Calculation on f(n+1) can be achieved with a new function:

\newcommand*{\mycommandB}[1]{%
\pgfmathparse{
ifthenelse(#1+1 < 1,#1+1,(#1+1)*(#1+1))}
\pgfmathresult
}%

-
Thank you for your answer, that's pretty much what I did. However, if I want to calculate f(x+1), it doesn't work, i.e. I can't pass the argument "\x+1" to the macro (in the "plot" line). Any way to work around that? – George Dec 29 '12 at 16:58

You can use the ifthen package together with intcalc. Then define a macro like this:

\newcommand{\test}[1]{\ifthenelse{#1<1}{#1}{\intcalcMul{#1}{#1}}

-