Re: Export a matrix in C form
- To: mathgroup at smc.vnet.net
- Subject: [mg89881] Re: Export a matrix in C form
- From: roby.nowak at gmail.com
- Date: Tue, 24 Jun 2008 03:19:59 -0400 (EDT)
- References: <g3ihro$fft$1@smc.vnet.net>
On 21 Jun., 11:32, Pavel Balaz <pavel.ba... at gmail.com> wrote: > Hi, > > I have a big matrix in Mathematica with elements given as function of > several parameters. I would like to export this matrix to C/C++ in > this general form. However, if I use CForm[], I obtain something like > List(List(cos(x),sin(y), ...), List(exp(x*y), ...), ...) > I have never seen such C/C++ code :-( > It is possible to save the matrix element to a single file containing > definitions all matrix elements in the form > double M[16][16]; > M[0][0]=cos(x); > M[0][1]=sin(x); > ... > > Thank you very much. Hi, love it or hate it: {{Cos[x], Sin[x]}, {-Sin[x], Cos[x]}} % // # /. {Cos[x_] -> "cos(x)", Sin[x_] -> "sin(x)"} & % // MapIndexed[ "M[" <> ToString[First@#2 - 1] <> "][" <> ToString[Last@#2 - 1] <> "]=" <> ToString@#1 <> ";\n" &, #, {2}] & // Flatten // StringJoin @@ # & {{Cos[x], Sin[x]}, {-Sin[x], Cos[x]}} {{"cos(x)", "sin(x)"}, {-"sin(x)", "cos(x)"}} M[0][0]=cos(x); M[0][1]=sin(x); M[1][0]=-sin(x); M[1][1]=cos(x);