简体   繁体   中英

Evaluate Matlab symbolic function

I have a problem with symbolic functions. I am creating function of my own whose first argument is a string. Then I am converting that string to symbolic function:

f =  syms(func)

Lets say my string is sin(x) . So now I want to calculate it using subs .

a = subs(f, 1)

The result is sin(1) instead of number.

For 0 it works and calculates correctly. What should I do to get the actual result, not only sin(1) or sin(2) , etc.?

You can use also use eval() to evaluate the function that you get by subs() function

f=sin(x);
a=eval(subs(f,1));
disp(a);
a =

    0.8415
syms x
f = sin(x) ;

then if you want to assign a value to x , eg pi/2 you can do the following:

subs(f,x,pi/2)
ans =

1

You can evaluate functions efficiently by using matlabFunction. syms stx =[ 2 - 5*t - 2*s, 9*s + 12*t - 5, 7*s + 2*t - 1]; x=matlabFunction(x); then you can type x in the command window and make sure that the following appears:

x

x =

@(s,t)[s.*-2.0-t.*5.0+2.0,s.*9.0+t.*1.2e1-5.0,s.*7.0+t.*2.0-1.0]

you can see that your function is now defined by s and t. You can call this function by writing x(1,2) where s=1 and t=1. It should generate a value for you.

Here are some things to consider: I don't know which is more accurate between this method and subs. The precision of different methods can vary. I don't know which would run faster if you were trying to generate enormous matrices. If you are not doing serious research or coding for speed then these things probably do not matter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM