I extensively use Comsol for my work and I use Mathematica to modify or create some expressions that I utilize in Comsol.
Comsol has the same syntax as Matlab (for the most part). Hence, I created a simple function that outputs an expression ready to be inputted in Comsol.
I use the fact that FortranForm
is pretty similar to Matlab, hence:
MatlabForm[L_List] := MatlabForm/@L
MatlabForm[expr_] := ToString@FortranForm[expr /. {
Complex[0, Rational[1, b_]] :> "1j"/MatlabForm@b,
Complex[0, Rational[a_, b_]] :> "1j"*MatlabForm[MatlabForm@a/MatlabForm@b],
Complex[0, b_] :> "1j"*MatlabForm@b,
Complex[a_, b_] :> MatlabForm@a + "1j"*MatlabForm@b,
a_^Rational[1,2] | Sqrt[a_] :> sqrt@MatlabForm@a,
E^x_ :> exp@MatlabForm@x,
Rational[1, b_] :> 1/MatlabForm@b,
Rational[a_, b_] :> MatlabForm[MatlabForm@a/MatlabForm@b],
(op:Abs|Cos|Sin|Tan|Exp)[x_] :> ToLowerCase[ToString@op][MatlabForm@x],
Conjugate[x_] :> "conj"@MatlabForm@x,
Re[x_] :> "real"@MatlabForm@x,
Im[x_] :> "imag"@MatlabForm@x
}] // StringReplace[#, {"**" -> "^", "\"" -> ""}] &
Which basically deals with some very basic (but nonetheless useful) operations/functions.
The final result also needs to human readable for debug purposes, so I created another function:
MatlabFormSimplify[expr_] := Block[{res},
ClearAttributes[{Plus, Times}, Orderless];
res = MatlabForm@Simplify[Simplify@expr, ComplexityFunction -> StringLength@*MatlabForm,
TransformationFunctions -> {
Automatic,
Function[{e}, e /. (op:Times|Plus)[a___, b_, c_, d___] :> op[a, c, b, d]]
}];
SetAttributes[{Plus, Times}, Orderless];
res
]
Which strip-out the Orderless attribute of Plus and Times, so b-a
never evaluates to -a+b
, which is ugly and has too many symbols.
A real example would be:
Cross[{Ax, Ay, Az}, Conjugate@{Bx, By, Bz}] // MatlabFormSimplify // TableForm
(* output *)
"conj(Bz)*Ay - conj(By)*Az"
"conj(Bx)*Az - conj(Bz)*Ax"
"conj(By)*Ax - conj(Bx)*Ay"
Compare with the standard Mathematica output:
{-Az Conjugate[By] + Ay Conjugate[Bz], Az Conjugate[Bx] - Ax Conjugate[Bz], -Ay Conjugate[Bx] + Ax Conjugate[By]}
PS: I don't usually output lists as Matlab [...], since, as I already said, I use Comsol, hence is more important to define scalar quantities based on symbolic expressions. PSS: More functions can be easily added. I rather created my own function, that I fine-tuned, than use an outdated Package.