Search code examples
matlabsymbolic-math

How to parse a symbolic expression in Matlab


In Matlab 2016a, Mathworks deprecated the use of the sym function for parsing symbolic expressions:

>> expr = sym('x + 1')
Warning: Support of strings that are not valid variable names or define a number will be
removed in a future release. To create symbolic expressions, first create symbolic
variables and then use operations on them. 
> In sym>convertExpression (line 1536)
  In sym>convertChar (line 1441)
  In sym>tomupad (line 1198)
  In sym (line 177) 

expr =

x + 1

The warning's suggestion is not practical when the symbolic expressions are being read from a file rather than built by hand in code. Is there a function in Matlab to replace this functionality? I would rather not regexprep and eval my way through it.


Solution

  • In Matlab 2017b, the str2sym function was added to replace the lost functionality of parsing a string into a symbolic expression. It works essentially like sym used to:

    >> expr = str2sym('x + 1')
    
    expr =
    
    x + 1