# Defining a function of matrices [closed]

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.

• Module and/or CompoundExpression?
– kglr
Apr 12, 2015 at 0:03
• I think Module can be the way to do that, so I have tried with the following code: Apr 12, 2015 at 3:24
• 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] Apr 12, 2015 at 3:24
• However, if I try with a simple example, like: F = getF[IdentityMatrix, IdentityMatrix, IdentityMatrix]; I do not get any result...how is that possible? Apr 12, 2015 at 3:26
• i posted as an answer what i think is the corrected version of your example.
– kglr
Apr 12, 2015 at 3:44

## 1 Answer

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];
Return[0.5*TraceF]]
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.