change class syms to double

39 次查看(过去 30 天)
what must i do to change a class sym to a class double?

采纳的回答

John D'Errico
John D'Errico 2023-4-10
编辑:John D'Errico 2023-4-10
If your sym variable still contains ANY symbolic parameters, then nothing can change it to a number. A double connot store a symbolic parameter. But if your variable is purely numeric, then yes, it is easy, just use the function double. For example:
phi = (1 + sqrt(sym(5)))/2
phi = 
format long g
dphi = double(phi)
dphi =
1.61803398874989
So dphi is a double precision number. you can do as you wish with it now.
But if a variable contains any unresolved symbolic parameter, for example
syms a
V = (3*a+2)/(a^2+1)
V = 
Now if I try to use double on V, it will certainly fail with an error (I'll show that at the end of this answer, since once Answers MATLAB sees an error, it will not continue to process other lines of code.) However, I could convert V into a function.
Vfun = matlabFunction(V)
Vfun = function_handle with value:
@(a)(a.*3.0+2.0)./(a.^2+1.0)
And now Vfun is back in the double precision universe, since it is just a function handle, something that normal MATLAB understands.
Vfun(2.3)
ans =
1.41494435612083
And now we can use Vfun by any tool that uses doubles.
fzero(Vfun,3)
ans =
-0.666666666666667
We can of course stuff a number into a. That will resolve the value of a. Then double will work.
double(subs(V,a,2.3))
ans =
1.41494435612083
But, as I said, here is what you should expect to see if you try to force V to be a double, without somehow resolving all symbolic parameters into numbers.
dV = double(V)
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 729)
Xstr = mupadmex('symobj::double', S.s, 0);

更多回答(1 个)

Paul
Paul 2023-4-10
Something like this ...
e = exp(sym(1))
e = 
e
class(e)
ans = 'sym'
format long
e = double(e)
e =
2.718281828459045
class(e)
ans = 'double'

类别

Help CenterFile Exchange 中查找有关 Assumptions 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by