MATLAB Answers

Converting strings to operators

8 views (last 30 days)
v k
v k on 26 Nov 2020
Commented: Walter Roberson on 26 Nov 2020
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.

Accepted Answer

Walter Roberson
Walter Roberson on 26 Nov 2020
S = '(2*3)+Z*14*(3*5)+(7)*(9)-(11)*13'
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;
newS = '(6)+Z*14*(15)+63-143'
newS = '(6)+Z*210+63-143'
newS = '(6)+Z*210+63-143'
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
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.
Walter Roberson
Walter Roberson on 26 Nov 2020
Shunting Yard got mentioned by other people a couple of times recently... they found it, not me :)

Sign in to comment.

More Answers (1)

Matt J
Matt J on 26 Nov 2020
Edited: Matt J on 26 Nov 2020
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
Name Size Bytes Class Attributes S 1x5 366 string
ans = 6
  1 Comment
Walter Roberson
Walter Roberson on 26 Nov 2020
If this is user input then evalc is dangerous as the user could have coded a call to delete files

Sign in to comment.


Community Treasure Hunt

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

Start Hunting!