MATLAB
8. Symbolic Toolbox
subs, eval
Variable substitution and expression evaluation: subs, eval
Suppose you have a symbolic expression f which includes the symbol x and you wish to substitute for x another symbol c or a numerical value x0. Then you can use the general subs command g=subs(f,old,new) which in our cases would be g=subs(f,x,c) or g=subs(f,x,x0). Here old, new can be arrays. The result g is still a symbolic variable or symbolic constant in “Maple”.
Example 1: Consider a function of the two Cartesian coordinates f(x, y) =
2xy/(x2 + y2)2 .
Change to polar coordinates using x = r cos θ, y = r sin θ and then determine the value of f at an arbitrary point on the unit circle r = 1.
clear all
syms x y r theta
f=2*x*y/(x^2+y^2)^2;
F=subs(f,[x y],[r*cos(theta) r*sin(theta)]);
F=simple(F) % previous answer is messy
f_on_unit_circle=subs(F,r,1)
which gives the output
F=sin(2*theta)/r^2
f_on_unit_circle=sin(2*theta)
An alternative is to use the eval command. It is of the form ans=eval(S) where S is a symbolic expression for which at least one of its symbolic variables has just been given a value. If all variables are given numerical values, the answer is a number in MATLAB, not “Maple”.
Example 2: Let us compare simple MATLAB and “Maple” codes which both evaluate the expression y = (x3 + 2) sec x at x = 0.123.
MATLAB code | Maple code using subs | Maple code using eval |
clear all | clear all | clear all |
x=0.123 | syms x | syms x |
y=(x^3+2)*sec(x) | S=(x^3+2)*sec(x); | S=(x^3+2)*sec(x); |
y=subs(S,x,0.123) | x=0.123; | |
y=double(y) | y=eval(S) |
Example 3: Reconsider Example 1 at the top of the page. Change the last line to the corresponding two lines in the following M-file:
clear all
syms x y r theta
f=2*x*y/(x^2+y^2)^2;
F=subs(f,[x y],[r*cos(theta) r*sin(theta)]);
F=simple(F)
r=1;
f_on_unit_circle=eval(F)