How to Convert symbolic variables to numeric

53 views (last 30 days)
Greetings!
How to convert a symbolic expression into a numerical expression?
best regards,
Walid.
  3 Comments

Sign in to comment.

Answers (1)

Steven Lord
Steven Lord on 25 Jan 2023
If it contains no symbolic variable use double.
two = sym(2);
sqrt2 = sqrt(two)
sqrt2 = 
x = double(sqrt2)
x = 1.4142
If it does contain a symbolic variable you can approximate the numeric parts with vpa. You could also use vpa even if it doesn't contain a symbolic variable.
z = vpa(sqrt2)
z = 
1.4142135623730950488016887242097
syms y
polynomialInY = y.^2 + sqrt2*y - 1
polynomialInY = 
vpa(polynomialInY)
ans = 
In this case trying to convert polynomialInY to a double array will error. You could subs a value for y into that expression (to eliminate the symbolic variable) then convert the result.
double(polynomialInY)
Error using symengine
Unable to convert expression containing symbolic variables into double array. Apply 'subs' function first to substitute values for variables.

Error in sym/double (line 872)
Xstr = mupadmex('symobj::double', S.s, 0);
  5 Comments
Steven Lord
Steven Lord on 25 Jan 2023
The description for the 'r' value for the flag input argument to the sym function lists the forms that it recognizes for "modest-sized integers p and q". This value for the flag input is the default which is why:
x = sym(sqrt(2))
x = 
works to give . 2 counts as "modest-sized".

Sign in to comment.

Categories

Find more on Get Started with Symbolic Math Toolbox in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!