Converting strings to operators
11 次查看(过去 30 天)
显示 更早的评论
I think this is a naive query. Yet, let me pose it:
If '(' '2' '*' '3' ')' are elements of a string vector S, then what function f results in the following:
f(S) = (2*3) = 6
str2num for '2' and '3' is not an option, since they can occur anywhere in S, and there is no apriori information as to where they will occur.
For the same reasons, keeping the bracket structure intact is also important, even though it seems that we can do away with the brackets in this example.
0 个评论
采纳的回答
Walter Roberson
2020-11-26
S = '(2*3)+Z*14*(3*5)+(7)*(9)-(11)*13'
while true
newS = regexprep(S, {'\((\d+)\)\*\((\d+)\)', '\((\d+)\)\*(\d+)', '(\d+)\*\((\d+)\)', '(\d+)\*(\d+)'}, {'${string(times(str2double($1),str2double($2)))}'})
if strcmp(newS, S); break; end
S = newS;
end
Note that the logic gets more complex if you have operators that are higher priority, such as ^ . For example '2*3^Z' should not have the 2*3 multiplied out.
Also, you could reasonably argue that I did not preserve brackets in some of the cases such as (11)*13 -- it would not be unreasonable to claim that the result of that should be (143) instead of 143 . You could take care of those cases by having four different replacement strings instead of the single replacement I have there.
I did try to unify all of the cases into one case, but stripping off the brackets without using nested regexp or using an auxillary function would have been a bit messy. It would probably be cleanest to use some auxillary functions like
{'${s_times($1,$2)}'}
with s_times responsible for stripping off brackets and converting to numeric and doing the multiplication and converting the result to character. It would probably be a good idea to use something like that, and then the cases could probably be reduced to a single case.
5 个评论
Walter Roberson
2020-11-26
Shunting Yard got mentioned by other people a couple of times recently... they found it, not me :)
更多回答(1 个)
Matt J
2020-11-26
编辑:Matt J
2020-11-26
I can't tell if you really intend S to be a string vector because that dpesn't agree with the example you posted. If I assume it is what you meant, though, then you could do,
S=["(" "2" "*" "3" ")"];
whos S
eval(cell2mat(cellstr(S)))
1 个评论
Walter Roberson
2020-11-26
If this is user input then evalc is dangerous as the user could have coded a call to delete files
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!