Evaluate Matlab symbolic function
Asked Answered
R

3

6

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

Rebec answered 17/11, 2013 at 15:25 Comment(0)
C
9

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
Caylacaylor answered 17/11, 2013 at 15:39 Comment(0)
A
4
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
Autochthon answered 17/11, 2013 at 15:33 Comment(0)
C
2

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.

Codex answered 7/6, 2016 at 3:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.