Math & Scienceifthenelse is not working properly

Information and discussion about LaTeX's math and science related features (e.g. formulas, graphs).
Post Reply
leo simon
Posts: 17
Joined: Wed Aug 19, 2009 5:41 pm

ifthenelse is not working properly

Post by leo simon »

Hi

I'm having trouble with the \ifthenelse command in the package ifthen.sty. The
following code illustrates the problem.
I'm conditioning on a defined variable \a being equal to another variable, either \b or something else. If \b is defined equal to a math command, e.g., \beta, the statement works, but if if \b is defined equal to either a letter (e.g., i) or a subscripted variable, \beta_i, then I get an error. Any advice as to how to get around this would be most appreciated. I want somehow to be able to condition on \b=\epsilon_i^j.

Code: Select all

\documentclass[11pt,reqno]{amsart}%
\usepackage{ifthen}
%If \b is defined as \beta, then \d is properly defined
%If \b is defined as i, then there is an error when \d is processed
%If \b is defined as \beta_i, then there is an error when \d is processed
\def\b{\beta}
\def\b{i}
\def\b{\beta_\rho}
\def\c{\gamma}
\def\d{
    \ifthenelse{\a=\b}{1}{0}}
\begin{document}
\def\a{\c}
$\d$
\def\a{\b}
$\d$
\end{document}

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

josephwright
Site Moderator
Posts: 814
Joined: Tue Jul 01, 2008 2:19 pm

ifthenelse is not working properly

Post by josephwright »

ifthenelse is trying to compare numbers, which you don't have. I'd do this with the TeX \ifx primitive:

Code: Select all

\documentclass[11pt,reqno]{amsart}%
\def\b{\beta}
\def\b{i}
\def\b{\beta_\rho}
\def\c{\gamma}
\def\d{\ifx\a\b 1\else 0\fi}
\begin{document}
\def\a{\c}
$\d$
\let\a\b %Note this line
$\d$
\end{document}
You'll also see that for the test to work, \a has to have the same definition as \b, not just be defined as \b. You could \protected@edef things to get around this, but I'd avoid it if possible and simply \let \a to equal \b.
Joseph Wright
Post Reply