I am translating my code from Python to Mathematica. How can I define a function similar to the following:

def getF(csi, a, b):
    csiInv = linalg.inv(csi)
    valueF = csiInv.dot(a).dot(csiInv).dot(b)
    traceF = valueF.trace()
    return 0.5 * traceF

where csi, a, b are all matrices? I know that in Mathematica the usual way of defining things, i.e. ":=", works only with one line following the ":=" sign, but if this was true then I wouldn't be able to "define" a similar funciton in Mathematica.

  • 1
    $\begingroup$ Module and/or CompoundExpression? $\endgroup$
    – kglr
    Apr 12, 2015 at 0:03
  • $\begingroup$ I think Module can be the way to do that, so I have tried with the following code: $\endgroup$
    – johnhenry
    Apr 12, 2015 at 3:24
  • $\begingroup$ getF[csi_, a_, b_] := Module[ {csiInv, valueF, TraceF, Csi, A, B}, Csi = csi; A = a; B = b; csiInv = Inverse[csi]; valueF = csiInv.a.csiInv.b; TraceF = Trace[valueF]; Return[0.5*traceF] $\endgroup$
    – johnhenry
    Apr 12, 2015 at 3:24
  • $\begingroup$ However, if I try with a simple example, like: F = getF[IdentityMatrix, IdentityMatrix, IdentityMatrix]; I do not get any result...how is that possible? $\endgroup$
    – johnhenry
    Apr 12, 2015 at 3:26
  • $\begingroup$ i posted as an answer what i think is the corrected version of your example. $\endgroup$
    – kglr
    Apr 12, 2015 at 3:44

1 Answer 1


Cleaning up the example in the comments:

ClearAll[getF, a, b, csi, csiInv, valueF, TraceF]
getF[csi_, a_, b_] :=  
  Module[{csiInv, valueF, TraceF}, 
    csiInv = Inverse[csi]; 
    valueF = csiInv.a.csiInv.b; TraceF = Tr[valueF]; 
getF[IdentityMatrix[3], IdentityMatrix[3], IdentityMatrix[3]]
(* 1.5 *)

Or, better yet,

getF2[csi_, a_, b_] := Module[{csiInv = Inverse[csi]}, .5 Tr[csiInv.a.csiInv.b]]
getF2[IdentityMatrix[3], IdentityMatrix[3], IdentityMatrix[3]]
(* 1.5 *)

Notes: (1) Tr is the function you need for the trace of a matrix, not Trace, (2) you need to use IdentityMatrix[n] instead of IdentityMatrix.


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