How to evaluate numeric expression in a string, which contains "12u" (for 12e-6) and "0.1m" (for 0.1e-3) formated numbers (standing for micro and milli)?
조회 수: 6 (최근 30일)
이전 댓글 표시
Hi,
I'd like to have a "supercharged" eval function, which would accept expressions where numbers can be given with 'm' (mili) or 'u' (micro extension.
Here is my naive approach is to define function seval
seval("1m") % works fine
seval(['10*(0.2m+20*3.1u)']) % works fine
seval('max(1u,2m)') % errors, since 'm' in 'max' is also replaced
function rez = seval(s)
s = strrep(s, 'u', 'e-6'); % micro
s = strrep(s, 'm', 'e-3'); % mili
s = strrep(s, 's', 'e-0'); % :-)
rez = eval(s);
end
This works fine for simple expressions, but obviously not for
seval('max(1u,2m)')
So, I'd like to replace 'm' with 'e-3', but only when 'm' follows a well formated number. Seems like a job for regexp, but I couldn't find an elegant way to solve this.
P.S. Bonus question:
I'd also like to use 'variables'. A way to acieve this is to replace e.g. '1+a' with '1+var(a)', but only when 'a' is "standalone factor" in the expression. Any ideas?
seval2('1m + a') % this would translate to ...
seval('1m + var(a)')
function rez = var(s) % an example of 'variable' function
switch s
case 'a'
rez =1;
case('b')
rez = 2;
otherwise
rez = 0;
end
end
댓글 수: 0
채택된 답변
Star Strider
2022년 10월 6일
str = 'max(1u,2m)';
out = seval(str)
str = 'max(1.5u,2.01m)';
out = seval(str)
function res = seval(s)
res = s;
res = regexprep(res, '(?<=\d)m','e-3');
res = regexprep(res, '(?<=\d)u','e-6');
res = regexprep(res, '(?<=\d)s','e-0');
end
The ‘Bonus question’ eludes me, likely because I am not confident that I understand it.
.
댓글 수: 3
추가 답변 (1개)
Steven Lord
2022년 10월 6일
I'd like to have a "supercharged" eval function
This doesn't sound like a good idea.
which would accept expressions where numbers can be given with 'm' (mili) or 'u' (micro extension.
I strongly recommend that instead of making a "supercharged" version of eval that you think smaller. A function that accepts a string or char vector containing a number followed by a suffix then:
- splits the text into the number part and the suffix part
- converts the number part to an actual double value then
- multiplies the double value by a scaling factor determined from the suffix
would be more focused and less likely to get you into trouble. The splitting may be a bit tricky, since the "number part" may contain digits, a decimal point, perhaps an arithmetic symbol, and potentially the letters 'd', 'e', 'i', and/or 'j'.
x = 1.23e-1+2i
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!