drhagen
drhagen

Reputation: 9532

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.

Upvotes: 3

Views: 1587

Answers (3)

drhagen
drhagen

Reputation: 9532

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

Upvotes: 3

horchler
horchler

Reputation: 18484

This syntax was originally deprecated in R2015b (archived documentation), though it has been clear that it was going to happen for many years. The warning has been added in R2016a. Who knows when this functionality will be fully removed.

You don't want to use eval, but that's effectively what the current symbolic engine uses when you pass it string expressions. Even after this syntax is removed, there will likely still be ways to call the MuPAD engine like this:

f1 = evalin(symengine,'2*x+y^2+1')

One "workaround" is of course to disable the warning in R2016a:

S = warning('off','MATLAB:singularMatrix'); % Change second string to correct MsgID
... % Do stuff
warning(S); % Reset warning state

Upvotes: 1

FurlongsGrix
FurlongsGrix

Reputation: 50

Check out this line from the Mathworks site on sym and syms: (my emphasis in bold)

To create symbolic expressions, first create symbolic variables, and then use operations on them. For example, use syms x; x + 1 instead of sym('x + 1') ...

There are several other examples after that, though this one speaks very exactly to your question. I'm not sure if that'll be compatible with the file you're reading. Hopefully so! Let me know if not, happy to try helping with any potential followup.

Upvotes: -2

Related Questions