[Tex/LaTex] How to sweave Matlab or Mathematica code into LaTeX.

MATLABsweave

There is a package called pgfsweave for R. It can sweave R code into a LaTeX document. I found we can gain some advantage from this method.

  1. The report document can reproduce.
  2. The font in figure keeps consistent with main font of document.

I think "sweave" code is the best method for data-oriented report (especially for LaTeX). By sweave, we can separate data (or figure) from the document, through LaTeX, we can separate content from document style.

Unfortunately, I didn't find a corresponding package or some equivalent method for matlab and mathematica.

I know some packages, like psfrag or matlab2tikz, that work well. But we need a more powerful tool to do this that can change our workflow and that can make our life easier.

Is that possible? How do you solve this problem? Does it meet the philosophy of matlab or mathematica?

Best Answer

There are three ways of doing this:

  1. Do the weaving at the application (Matlab, Mathematica, R) end. That is, the application should be aware of the TeX format and ignore everything other than \begin{code} ... \end{code} snippets. This is how Sweave and literate haskell work.

  2. Do the weaving at the TeX end, that is, let TeX call the external application (with appropriate switches) and then display the result. This the approach that the R and gnuplot modules in ConTeXt follow.

  3. Use a general purpose literate programming tool, like noweb (or those targeted to a specific language like Ocamweb).

For the second approach, I have written a ConTeXt module, filter, that allows you to pass the content of a program to an external program and read back the results. For example, you can replicate the functionality of sweave using:

\usemodule[filter]

\defineexternalfilter
  [R]
  [filtercommand={R CMD BATCH -q --save --restore \externalfilterinputfile\space \externalfilteroutputfile},
   output=\externalfilterbasefile.out,
   readcommand=\typefile,
   continue=yes]

Then, using

\startR
  ...
\stopR

will execute the resultant code using R and show the output generated by R. Using

\startR[read=no]
  ....
\stopR

will execute the code using R but not show the output. The same approach will work for Matlab or Mathematica by replacing the filtercommand by the appropriate call to Matlab/Mathematica. This approach can be used for other purposes as well