MATLAB Answers

Convert numerical equations to latex

29 views (last 30 days)
Oliver Wan
Oliver Wan on 15 Aug 2020
Edited: Oliver Wan on 15 Aug 2020
Hi guys,
Im very very new to MATLAB and im trying to write some code to convert numerical equations to latex code. I have found that it is quite easy to do with symbolic variables, however not with "double" data types. I have tried converting the doubles to symbolic variables using
var = 1.234567890
sym_var = sym(var)
latex(sym_var)
However it often automatically converts the decimals to fractions which is undesireable.
Ive thought of workarounds but they are not very easy to replace and require a long time to code.
Ultimately, my goal is to acheive something like this very simple example:
%==== Numerical Values (Unrounded) ==============
a = 12838721234789
b = 2388284
c = 3822.2847272
%================================================
d = a + b/c
to return or print:
"d = 1280000+\frac{2340000}{3820} = 12384496.83"
or even:
I also wish for the code to work with very long and complicated equations, not just the simple example shown above.
Note that the output is a string containing all latex code required to display ANY numerical equation stored in "d" (including "d =" and the equivalent final answer for the equation). It also has all numerical values rounded to an easy to specify number of significant figures (in this case 3) excluding the final answer (which is always rounded to 10 sig figs).

  0 Comments

Sign in to comment.

Answers (1)

J. Alex Lee
J. Alex Lee on 15 Aug 2020
Assuming the results will always be integers, here's a simple way
%==== Numerical Values (Unrounded) ==============
a = 1283872
b = 2388284
c = 3822.2847272
%================================================
d = a + b/c
s = 3
str = sprintf('d = %d + \\frac{%d}{%d}',...
round(a,s,'significant'),...
round(b,s,'significant'),...
round(c,s,'significant'))

  1 Comment

Oliver Wan
Oliver Wan on 15 Aug 2020
Hi Alex, my apologies, I did not specify that the example I gave was only a very simple example. Im looking for a solution that works for very long equations with many constant terms. It is also the case that the results are not always integers.
I apologise once again for my poor communication on my behalf.
Thank you for your response!

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!