user2141889
user2141889

Reputation: 2305

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.?

Upvotes: 6

Views: 20400

Answers (3)

mike k
mike k

Reputation: 21

You can evaluate functions efficiently by using matlabFunction. syms s t x =[ 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.

Upvotes: 2

xor
xor

Reputation: 2698

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

Upvotes: 9

Chris
Chris

Reputation: 470

syms x
f = sin(x) ;

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

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

1

Upvotes: 4

Related Questions