本文介绍了Matlab:正则表达式将字符串中的长小数点转换为小数点后一定位数的小数点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下字符串.我想匹配所有小数位数,例如regexp(myS, '\.[0-9]+', 'match'),然后删除小数点后的多余数字.您如何在Matlab中做到这一点?

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?

输入字符串

\left(\begin{array}{ccc} 0.0000000000011 & 0.0023245508539986303730984218418598 & 0.0023219396894162969147146213799715 & 0.0023237598123344582745630759745836 \end{array}\right)

字符串输出

\left(\begin{array}{ccc} 0.000000 0.002324 & 0.002321 & 0.002323 \end{array}\right)

Harder目标输出字符串

\left(\begin{array}{ccc} 1.100E-12 & 2.324E-3 & 2.321E-3 & 2.323E-3 \end{array}\right)

P.s.我在这里考虑这个难题的解决方案候选,以尝试将结果从Matlab很好地转换为LaTex.

P.s. I am considering here a solution candidate to this puzzle here in trying to convert the results nicely from Matlab to LaTex.

推荐答案

我建议对动态替换表达式使用regexprep:

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)

编辑

刚注意到它说更难的 output 字符串"-这是实现该目标的方法(尽管它确实总是带有两位数的指数).当然,如果您不想匹配指数符号,则可以在match表达式中省略E-.

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)

这篇关于Matlab:正则表达式将字符串中的长小数点转换为小数点后一定位数的小数点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:18