I am doing some tensor multiplication operations and would like to have Mathematica generate C code so that I can use it later.
I want to supply two 2nd order tensors(A and B) and get the entries of a 4th order tensor as a function of the inputs A and B.
However, I am having problems getting the output.
Currently, I have:
ClearAll[a,b]
(* define tensor a and b as symmetric*)
SetAttributes[a,Orderless];
SetAttributes[b,Orderless];
tensorA = Array[a,{3,3},0];
tensorB = Array[b,{3,3},0];
g= 1-4*Det[tensorA];
(* define my operation *)
result = TensorProduct[tensorA,tensorB]+g*TensorTranspose[TensorProduct[tensorA,tensorB],{1,3,2,4}]
(* Generate C code *)
(*How can I generate C code?*)
CAssign[result]
Additionally, to generate better C code, should I define:
g= 1-4*Det[tensorA];
or
g= 1.0-4.0*Det[tensorA];
With the first I get the result of CAssign as fractions, with the second as floating point. Does this make a difference?
The expected output should be something like:
// entries of the input tensors
double var1 = a(0,0)
double var5 = a(1,1)
double var9 = a(2,2)
double var10 = b(0,0)
double var14 = b(1,1)
double var18 = b(2,2)
result(0,0,0,0)=var1 * var10
result(0,0,0,1)=...
result(0,0,0,2)=...
and so on
Best Regards!
CForm
and the undocumentedExperiment`OptimizeExpression
. (Search this site for it.) $\endgroup$Compile
is then able to unroll this to a couple of multiplications which are by an order of magnitude faster thanpow
in C. $\endgroup$