user1543042
user1543042

Reputation: 3440

Matlab convert anonymous function to Latex expression

I want to pretty print an anonymous function, so I found the function latex (which only takes symbolic expressions) to do this:

f =@(x,a) (x/a) * exp(-x.^2 / (2*a^2));
latex(sym(f))

which outputs:

\frac{x\, \mathrm{e}^{-\frac{x^2}{2\, a^2}}}{a}

However, the above LaTeX syntax is not in the way I originally entered in the function. I would like the LaTeX syntax to appear in the same fashion I originally wrote it out, like the following:

\frac{x}{a} \mathrm{e}^{-\frac{x^2}{2\, a^2}}

I'd also be willing to start with a string. Is there a way to do this in MATLAB?

Upvotes: 4

Views: 542

Answers (1)

horchler
horchler

Reputation: 18484

As @thewaywewalk points out, an expression converted to symbolic math is "simplified" according to Matlab's rules. Here's an approach to avoid that. First you need to convert your numeric function to a suitable string (get rid of argument list, remove element-wise operators) and then convert it to a symbolic expression while calling MuPAD's hold:

f = @(x,a) (x/a) * exp(-x.^2 / (2*a^2));
fstr = regexprep(func2str(f), '^@\(.*?\)|\.', '') % Remove arguments, element-wise operators
fsym = feval(symengine, 'hold', fstr)             % Convert to symbolic expression
latex(fsym)

This returns:

\left(\frac{x}{a}\right)\, \mathrm{e}^{- \frac{x^2}{2\, a^2}}

which looks like:

LaTeX expression

I'm not sure how reliable this scheme will be in more complex cases as conversion from math to LateX is ill-defined. If you want particular precise LaTeX expressions (e.g., parentheses in particular places but not others), you'll need to write or edit them yourself or come up with your own conversion function.

Upvotes: 3

Related Questions