4

I am writing out equations and a lot of my equations have parameters changed but the basic structure is repeated.

I have reduced the problem to a hypothetical example as follows.

if (condition ==2) {
    p = 2*(x^2)
} else if (condition ==3) {
    p = 3*(x^3)
}

print(p)

Please note the storing and the retrieving are both the features which is required. I am not very sure if it is possible with latex but I believe the authors of latex ( being computer scientist) must have thought about it.

In case somebody has some idea as to how to execute it then kindly tell me.

  • 4
    Do you mean something like \newcommand\nxton[1]{p = #1 x^{#1} } which is then used as: $\nxton{2}$ ? – yo' Nov 10 '15 at 19:23
  • 2
    Another innocent mind drawn to the black hole of TeX programming. – percusse Nov 10 '15 at 19:37
  • Do you mean something like \documentclass{article} \begin{document} \def\condition{3} \ifnum\condition=2\relax\def\p{2*(x^2)}\else \ifnum\condition=3\relax\def\p{3*(x^3)}\fi \fi \detokenize\expandafter{\p} \end{document} – Steven B. Segletes Nov 11 '15 at 6:03
3

If you can use LuaLaTeX instead of either pdfLaTeX or XeLaTeX, it's straightforward to set up Lua functions along the lines of the example you gave as well as TeX "wrapper macros" that call the Lua functions with the required inputs.

enter image description here

% !TEX TS-program = lualatex
\documentclass{article}

%% Lua-side code
\usepackage{luacode}
\begin{luacode}
function pfunc ( cond , x )
   local p = 0
   x = tonumber ( x )
   if cond == "2" then
      p = 2*x^2 
   elseif cond == "3" then
      p = 3*x^3 
   end
   tex.sprint ( p ) 
end
\end{luacode}

%% TeX-side code
\newcommand\pfunc[2]{\directlua{ pfunc ( \luastring{#1} , \luastring{#2})}}

\begin{document}
\pfunc{2}{2}, \pfunc{3}{3}, \pfunc{1}{111}
\end{document}
  • I am not sure from the OP whether he wanted the computations done or only typeset... – user4686 Nov 10 '15 at 22:26
  • @jfbu - I'm not entirely sure either. The expression "the storing and the retrieving are both the features which [are] required" led me to believe that the function must actually do something, rather than just be printed out. Let's see if the OP weighs in and clarifies his/her objective. – Mico Nov 10 '15 at 22:30
  • perhaps he indeed wants to evaluate the expression and store the value in a p to be "retrieved" later if needed. As you say, only OP can clarify! – user4686 Nov 10 '15 at 22:33
  • Hi Jfbu, you are right. I am looking at the function actually doing something rather than just retrieving. – user2714795 Nov 11 '15 at 11:37
  • @user2714795 - Please give an example or two of what you mean by "actually doing something". – Mico Nov 11 '15 at 11:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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