2
$\begingroup$

I'm not experienced with Mathematica, but am learning to appreciate its awesome power for manipulations.

I get the an expression like this when using CForm (I cut it short to simplify):

T(0, 0) + ht*((-((T(-1, 0) + T(0, 0))*u(-0.5, 0)) 

In Mathematica, T, u are functions. But they should be arrays in my C code. Can I tell Mathematica that when it is exporting T, u to C, it should treat them as arrays and use []?

$\endgroup$
1
$\begingroup$

Update: I haven't written any C in a long while, so I forgot its syntax for multidimensional arrays, i.e. array[first][second]! Here is the amended code:

ToString[CForm[t[12, 156] + ht u[5, 3]]]

StringReplace[%, {
  "t(" ~~ Shortest[a__] ~~ "," ~~ Shortest[b__] ~~ ")" -> "t[" ~~ a ~~ "][" ~~ b ~~ "]", 
  "u(" ~~ Shortest[a__] ~~ "," ~~ Shortest[b__] ~~ ")" -> "u[" ~~ a ~~ "][" ~~ b ~~ "]"
  }]

(* Out: "t[12][156] + ht*u[5][3]" *)

Original answer: If it is acceptable to you to deal with strings for your C code, you could convert to a string, then apply a string pattern:

ToString[CForm[t[12, 156] + ht u[5, 3]]]

StringReplace[%,
 {
  "t(" ~~ Shortest[a__] ~~ "," ~~ Shortest[b__] ~~ ")" -> "t[" ~~ a ~~ "," ~~ b ~~ "]",
  "u(" ~~ Shortest[a__] ~~ "," ~~ Shortest[b__] ~~ ")" -> "u[" ~~ a ~~ "," ~~ b ~~ "]"
  }
]

(* Out: "t[12,156] + ht*u[5,3]" *)

The Shortest[a__] forms are there to handle cases in which the arguments to the functions are longer than one character.

$\endgroup$
  • $\begingroup$ thanks for the input. However, this seems to not work more generally: If I throw in a few exta parentheses inside what I want to become square-brackets, Mathematica gets the pattern wrong. $\endgroup$ – Yair Daon May 10 '15 at 19:14
1
$\begingroup$

Mathematica's CForm will convert Part expressions to arrays, so you can achieve what you want by changing your functions to Part expressions:

ReplaceAll[
    HoldForm[T[0,0]+ht (-(T[-1,0]+T[0,0]) u[-.5,0])],
    {T[a_,b_]:>T[[a,b]], u[a_,b_]:>u[[a,b]]}
] //CForm

T[0][0] + ht*(-(T[-1][0] + T[0][0])*u[-0.5][0])

Another possibility is to teach CForm about your functions:

Format[T[a_, b_], CForm] := HoldForm[T[[a, b]]]
Format[u[a_, b_], CForm] := HoldForm[u[[a, b]]]

Your example:

T[0,0]+ht (-(T[-1,0]+T[0,0]) u[-.5,0]) //CForm

T[0][0] + ht*(-T[-1][0] - T[0][0])*u[-0.5][0]

$\endgroup$

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.