How to simplify a symbolic and numeric mixed expression in Matlab

这一生的挚爱 提交于 2019-12-10 23:29:40

问题


I have a symbolic and numeric mixed expression:

(3145495418313256125*sin(11334310783410932061962315977/17437937757178560512000000000)*cos(theta))/85568392920039424

where theta is a symbolic variable. I want to simplify this expression such that all the numeric numbers and their math operation results are changed to double.


回答1:


In terms of data types, you can't mix floating point and symbolic values. However, you can use variable precision arithmetic so that the values are represented in decimal form. Using vpa:

syms theta
y1 = (3145495418313256125*sin(11334310783410932061962315977/17437937757178560512000000000)*cos(theta))/85568392920039424
y2 = vpa(y1)

which returns

y2 =

22.24607614528243677915796931637*cos(theta)

The data type (class) of y2 is still sym. See the digits function to adjust the number of significant digits.

If you want to work in actual floating point you'll need to convert your symbolic expression into a function. You can automate that procedure by using the confusingly-named matlabFunction:

thetafun = matlabFunction(y1)

which returns a function using double precision variables:

thetafun = 

@(theta)cos(theta).*2.224607614528244e1

The anonymous function thetafun can then be called just like any function, e.g., thetafun(0.5).




回答2:


You can make use of coeffs command to achieve the desired:

f=2*cos(theta)/3+5*sin(theta)/19
c_f=coeffs(f);
fraction_c_f=double(c_f);

ans = [0.2632  0.6667]


来源:https://stackoverflow.com/questions/22277525/how-to-simplify-a-symbolic-and-numeric-mixed-expression-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!