Using a Symbolic Expression
Show older comments
Hello,
I have one function that creates a symbolic expression for a variable, which is often lengthy. In another function, I am loading that symbolic expression and would like to evaluate that symbolic expression based upon parameters defined above.
For example, in my first function I solve for x to have the symbolic expression SymExpr = a*b*c. In my second function, I have a, b, and c defined as numeric values. I then load the saved symbolic expression SymExpr. I tried saying x = SymExpr, but this makes x a symbolic variable and x = char(SymExpr) but this makes x a string. I want x to be a double and I want to obtain the numeric value.
I know I could do this by just copying and pasting in the second function x = a*b*c, but my expressions from the first function can get very lengthy, so I'm trying to do this without having to copy/paste.
Thank you,
Kevin
1 Comment
Kevin Bachovchin
on 10 Apr 2013
Accepted Answer
More Answers (1)
Iman Ansari
on 10 Apr 2013
Hi
syms a b c;
SymExpr = a*b*c;
x=subs(SymExpr,[a b c],[1 2 3])
or
syms a b c;
SymExpr = a*b*c;
a=1;b=2;c=3;
x=subs(SymExpr)
15 Comments
Kevin Bachovchin
on 10 Apr 2013
Iman Ansari
on 10 Apr 2013
May x=eval(SymExpr) help you but:
Kevin Bachovchin
on 10 Apr 2013
Iman Ansari
on 10 Apr 2013
May i see your expression?
Kevin Bachovchin
on 10 Apr 2013
Iman Ansari
on 11 Apr 2013
clear all;
close all;
tic
syms omega tauL B M iR iSa theta iSb iSc J
domegadt = -(2*tauL + 2*B*omega + 2*M*iR*iSa*sin(theta) - M*iR*iSb*sin(theta) - M*iR*iSc*sin(theta) - 3^(1/2)*M*iR*iSb*cos(theta) + 3^(1/2)*M*iR*iSc*cos(theta))/(2*J);
domegadt=subs(domegadt,[omega tauL B M iR iSa theta iSb iSc J],[1+7.6765776i 2.8788798+765i 4.7687 1.878 8.13233+0.576i 5.876886 57.87 pi/7.65765 64343+3543i 90])
toc
domegadt =
2.9433e+03 + 3.6315e+02i
Elapsed time is 0.966587 seconds.
Kevin Bachovchin
on 11 Apr 2013
Edited: Kevin Bachovchin
on 11 Apr 2013
Iman Ansari
on 11 Apr 2013
Edited: Iman Ansari
on 11 Apr 2013
May this is what you want:
syms a b c;
SymExpr = a*b*c;
x=char(SymExpr);
a=1;b=2;c=3;
eval(['x=' x]);
or
x=eval(x)
Kevin Bachovchin
on 11 Apr 2013
Walter Roberson
on 11 Apr 2013
matlabFunction() to create a function handle that is what you would pass into ode45
Kevin Bachovchin
on 11 Apr 2013
Kevin Bachovchin
on 11 Apr 2013
Iman Ansari
on 11 Apr 2013
syms a b c;
SymExpr = a*b*c;
x=matlabFunction(SymExpr);
a=1;b=2;c=3;
x(a,b,c)
Or
x(1,2,3)
Kevin Bachovchin
on 11 Apr 2013
Kevin Bachovchin
on 11 Apr 2013
Categories
Find more on Common Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!