Reputation: 52840
I have the string as below. I would like to match all decimal numbers like regexp(myS, '\.[0-9]+', 'match')
and then remove the excess digits after the decimal point. How can you do it in Matlab?
Input String
\left(\begin{array}{ccc} 0.0000000000011 & 0.0023245508539986303730984218418598 & 0.0023219396894162969147146213799715 & 0.0023237598123344582745630759745836 \end{array}\right)
String Outputs
Easy Intended output string
\left(\begin{array}{ccc} 0.000000 0.002324 & 0.002321 & 0.002323 \end{array}\right)
Harder Intended output string
\left(\begin{array}{ccc} 1.100E-12 & 2.324E-3 & 2.321E-3 & 2.323E-3 \end{array}\right)
P.s. I am considering here a solution candidate to this puzzle here in trying to convert the results nicely from Matlab to LaTex.
Upvotes: 1
Views: 209
Reputation: 74940
I suggest using regexprep
with dynamic replacement expression:
regexprep(inputString,'([0-9\.E-]+)','${sprintf(''%8.6f'',str2double($0))}')
Here's the result for the first string (note: it's rounding "correctly", rather than chopping off digits)
\left(\begin{array}{ccc} 0.000000 & 0.002325 & 0.002322 & 0.002324 \end{array}\right)
Here is the result for the second, harder, input string
\left(\begin{array}{ccc} 0.000000 & 0.002324 & 0.002321 & 0.002323 \end{array}\right)
EDIT
Just noticed that it says "harder output string" - here's how to achieve that (though it does come with an always two-digit exponent). You can, of course, leave out the E-
in the match expression if you don't want to match exponential notations.
out = regexprep(instr,'([0-9\.E-]+)','${sprintf(''%5.3e'',str2double($0))}')
ans =
\left(\begin{array}{ccc} 1.100e-12 & 2.325e-03 & 2.322e-03 & 2.324e-03 \end{array}\right)
Upvotes: 2