Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question
    
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
add comment

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

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers

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:

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
}%
share|improve this answer
    
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
add comment

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}}
share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.