Symbolic Computation With Matlab: Symbolic Manipulations Symbolic Objects
Symbolic Computation With Matlab: Symbolic Manipulations Symbolic Objects
Symbolic Computation With Matlab: Symbolic Manipulations Symbolic Objects
Symbolic computation refers to the automatic transformation of mathematical expressions in symbolic form, hence in an exact way, as opposed to numerical and hence limited-precision floating-point computation. Typical operations include differentiation and integration, linear algebra and matrix calculus, operations with polynomials, or the simplification of algebraic expressions.
A S S O C . P RO F. D R. E L IF S E RT E L
s er tele@itu. ed u. tr
Numerical Variables represent numbers Answers can only be members Numeric computations can be done using standard programming languages
5/6/2010
Symbolic Variables Answers can contain variables and functions Symbolic computations are not similar to standard programming languagesthey use symbolic manipulations
5/6/2010
Symbolic Manipulations
3
Symbolic Objects
4
Available in the Symbolic Math Toolbox which is completely installed in the professional version The Symbolic Math Toolbox defines a new MATLAB data type called a symbolic object.
Symbolic objects are a special MATLAB data type introduced by the Symbolic Math Toolbox software. They allow you to perform mathematical operations in the MATLAB workspace analytically, without calculating numeric values. You can use symbolic objects to perform a wide variety of analytical computations:
Differentiation, including partial differentiation Definite and indefinite integration Taking limits, including one-sided limits Summation, including Taylor series Matrix operations Solving algebraic and differential equations Variable-precision arithmetic Integral transforms Symbolic objects present symbolic variables, symbolic numbers, symbolic expressions and symbolic matrices.
5/6/2010
5/6/2010
5/6/2010
Symbolic Variables
5
Symbolic Variables
6
You can use sym or syms to create symbolic variables. The syms command:
Does not use parentheses and quotation marks: syms x Can create multiple objects with one call Serves best for creating individual single and multiple symbolic variables
You can manipulate the symbolic objects according to the usual rules of mathematics. For example:
>>x + x + y >>ans = 2*x + y
create a symbolic variable x with the value x assigned to it in the MATLAB workspace and a symbolic variable a with the value alpha assigned to it. An alternate way to create a symbolic object is to use the syms command:
syms x; a = sym('alpha');
5/6/2010
Symbolic Numbers
7
Symbolic Numbers
8
Symbolic Math Toolbox software also enables you to convert numbers to symbolic objects. To create a symbolic number, use the sym command:
a = sym('2')
If you create a symbolic number with 10 or fewer decimal digits, you can skip the quotes:
a = sym(2)
The following example illustrates the difference between a standard doubleprecision MATLAB data and the corresponding symbolic number. The MATLAB command
sqrt(2)
or more efficiently:
sym(2/5) ans = 2/5
returns a double-precision floating-point number: ans = 1.4142 On the other hand, if you calculate a square root of a symbolic number 2:
a = sqrt(sym(2))
MATLAB performs arithmetic on symbolic fractions differently than it does on standard numeric fractions. By default, MATLAB stores all numeric values as double-precision floating-point data. For example:
2/5 + 1/3 ans = 0.7333
Symbolic results are not indented. Standard MATLAB double-precision results are indented. The difference in output form shows what type of data is presented as a result.
5/6/2010
If you add the same fractions as symbolic objects, MATLAB finds their common denominator and combines them in the usual procedure for adding rational numbers:
sym(2/5) + sym(1/3) ans = 11/15
5/6/2010
5/6/2010
Examples
9
The command
rho = sym('(1 + sqrt(5))/2');
NOTE: In the symbolic math mode, variables are not matrices Do not use .*, .^, or ./ operators create multiple variables
>>syms Q R T D0
achieves this goal. Now you can perform various mathematical operations on rho. For example,
f = rho^2 - rho - 1returns f = (5^(1/2)/2 + 1/2)^2 - 5^(1/2)/2 - 3/2
Now suppose you want to study the quadratic function f = ax2 + bx + c. One approach is to enter the command
f = sym('a*x^2 + b*x + c');
which assigns the symbolic expression ax2 + bx + c to the variable f. However, in this case, Symbolic Math Toolbox software does not create variables corresponding to the terms of the expression: a, b, c, and x. To perform symbolic math operations on f, you need to create the variables explicitly. A better alternative is to enter the commands
a = sym('a'); b = sym('b'); c = sym('c'); x = sym('x');
or simply
syms a b c x
Then, enter
5/6/2010 f = a*x^2 + b*x + c; 5/6/2010
A particularly effective use of sym is to convert a matrix from numeric to symbolic form. The command
A = hilb(3)generates the 3-by-3 Hilbert matrix: A = 1.0000 0.5000 0.3333 0.5000 0.3333 0.2500 0.3333 0.2500 0.2000
By applying sym to A
A = sym(A)
You can obtain the precise symbolic form of the 3-by3 Hilbert matrix:
A = [ 1, 1/2, 1/3] [ 1/2, 1/3, 1/4] [ 1/3, 1/4, 1/5]
5/6/2010
5/6/2010
5/6/2010
Symbolic Functions
14
You can substitute a numeric value for a symbolic variable or replace one symbolic variable with another using the subs command. To evaluate an expression, use the subs command
>> subs(S, old, new) replaces OLD with NEW in the symbolic expression S. OLD is a symbolic variable, a string representing a variable name, or a string (quoted) expression. NEW is a symbolic or numeric variable or expression.
When your expression contains more than one variable, you can specify the variable for which you want to make the substitution. For example, to substitute the value x = 3 in the symbolic expression,
>> syms x y >> f = x^2*y + 5*x*sqrt(y) >> subs(f, x, 3) ans = 9*y+15*y^(1/2) >> subs(f, x, z) %Can substitute a new variable ans = (z)^2*y + 5*(z)*sqrt(y)
5/6/2010
http://www.mathworks.com/access/helpdesk/help/toolbox/symbolic/f3-157665.html
5/6/2010
Symbolic Functions
15
Symbolic Functions
16
factor - Factorization
Syntax
factor(X)
Description
R = collect(S) returns an array of collected polynomials for each polynomial in the array S of polynomials. R = collect(S,v) collects terms containing the variable v.
Description
factor(X) can take a positive integer, an array of symbolic expressions, or an array of symbolic integers as an argument. If N is a positive integer, factor(N) returns the prime factorization of N.
Example
syms x y; R1 = collect((exp(x)+x)*(x+2)) return R1 = x^2 + (exp(x) + 2)*x + 2*exp(x)
Description
expand(S) writes each element of a symbolic expression S as a product of its factors. expand is often used with polynomials. It also expands trigonometric, exponential, and logarithmic functions.
If S is a matrix of polynomials or integers, factor(S) factors each element. If any element of an integer array has more than 16 digits, you must use sym to create that element, for example, sym('N'). Examples
Factorize the two-variable expression: syms x y; factor(x^3-y^3)The result is: ans = (x - y)*(x^2 + x*y + y^2)
Example
syms x; expand((x-2)*(x-4))The result is: ans = x^2 - 6*x + 8 5/6/2010
5/6/2010
5/6/2010
poly2sym function
17
Sym2poly function
18
Description
r = poly2sym(c) returns a symbolic representation of the polynomial whose coefficients are in the numeric vector c. The default symbolic variable is x. The variable v can be specified as a second input argument. If c = [c1 c2 ... cn], r = poly2sym(c) has the form poly2sym uses sym's default (rational) conversion mode to convert the numeric coefficients to symbolic constants. This mode expresses the symbolic coefficient approximately as a ratio of integers, if sym can find a simple ratio that approximates the numeric value, otherwise as an integer multiplied by a power of 2. r = poly2sym(c, v) is a polynomial in the symbolic variable v with coefficients from the vector c. If v has a numeric value and sym expresses the elements of c exactly, eval(poly2sym(c)) returns the same value as polyval(c, v).
Description
c = sym2poly(s) returns a row vector containing the numeric coefficients of a symbolic polynomial. The coefficients are ordered in descending powers of the polynomial's independent variable. In other words, the vector's first entry contains the coefficient of the polynomial's highest term; the second entry, the coefficient of the second highest term; and so on.
Example
poly2sym([1 3 2]) returns ans = x^2 + 3*x + 2
Example
syms x u v sym2poly(x^3 - 2*x - 5) returns ans = 1 0 -2 -5
5/6/2010
5/6/2010
Solution of Equations
19
Example
20
Description
Single Equation/Expression
The input to solve can be either symbolic expressions or strings. If eq is a symbolic expression (x^2 - 2*x + 1) or a string that does not contain an equal sign ('x^2 - 2*x + 1'), then solve(eq) solves the equation eq = 0 for its default variable (as determined by symvar). solve(eq, var) solves the equation eq (or eq = 0 in the two cases cited above) for the variable var.
System of Equations
The inputs are either symbolic expressions or strings specifying equations. solve(eq1, eq2, ..., eqn) or solves the system of equations implied by eq1,eq2,...,eqn in the n variables determined by applying symvar to the system. g = solve(eq1, eq2, ..., eqn, var1, var2, ..., varn) finds the zeros for the system of equations for the variables specified as inputs. Three different types of output are possible. For one equation and one output, the resulting solution is returned with multiple solutions for a nonlinear equation. For a system of equations and an equal number of outputs, the results are sorted alphabetically and assigned to the outputs. For a system of equations and a single output, a structure containing the solutions is returned.
5/6/2010
5/6/2010
5/6/2010
Plotting
21
Example
22
x2 - y4 = 0
over the domain [2, 2].
>>syms x y >>ezplot(x^2-y^4)
Syntax
ezplot(f) ezplot(f,[xmin xmax]) ezplot(f,[xmin xmax], fign) ezplot(f,[xmin, xmax, ymin, ymax]) ezplot(x,y) ezplot(x,y,[tmin,tmax]) ezplot(...,figure)
5/6/2010
5/6/2010
Example
23
Derivative
24
Matlab returns:
g= 3*x^2+sin(x)
Note that the command "diff" was used to obtain derivative of function f. If there are more than independent variable in a function, you should include "intended" variable in the following format: diff(f, x) where the "intended" variable.
>> syms x y >> f=x^2+(y+5)^3; >> diff(f,y)
Matlab returns:
ans = 3*(y+5)^2
5/6/2010 5/6/2010
5/6/2010
Integral
25
Matlab returns:
ans = 1/3*x^3+(y+5)^3*x
f ( x, y ).dy
0
5/6/2010
5/6/2010
Summations
27
symsum - Evaluate symbolic sum of series Syntax
r = symsum(expr) r = symsum(expr, v) r = symsum(expr, a, b)
Taylor series
28
Description
r = symsum(expr) evaluates the sum of the symbolic expression expr with respect to the default symbolic variable defaultVar determined by symvar. The value of the default variable changes from 0 to defaultVar 1. r = symsum(expr, v) evaluates the sum of the symbolic expression expr with respect to the symbolic variable v. The value of the variable v changes from 0 to v - 1. r = symsum(expr, a, b) evaluates the sum of the symbolic expression expr with respect to the default symbolic variable defaultVar determined by symvar. The value of the default variable changes from a to b.
Description
taylor(f) returns the fifth order Maclaurin polynomial approximation to f. taylor(f, n) returns the (n-1)-order Maclaurin polynomial approximation to f. Here n is a positive integer. taylor(f, a) returns the fifth order Taylor series approximation to f about point a. Here a is a real number. If a is a positive integer or if you want to change the expansion order, use taylor(f,n,a) to specify the base point and the expansion order. taylor(f, n, v) returns the (n-1)-order Maclaurin polynomial approximation to f, where f is a symbolic expression representing a function and v specifies the independent variable in the expression. v can be a string or symbolic variable.
Examples Evaluate the sum of the following symbolic expressions k and k^2:
syms k symsum(k) symsum(k^2) The results are ans = k^2/2 - k/2 ans = k^3/3 - k^2/2 + k/6
If a is neither an integer nor a symbol or a string, you can supply the arguments n, v, and a in any order. taylor determines the purpose of the arguments from their position and type. You also can omit any of the arguments n, v, and a. If you do not specify v, taylor uses symvar to determine the function's independent variable. n defaults to 6, and a defaults to 0.
5/6/2010 5/6/2010
5/6/2010
The following expression present the Taylor series for an analytic function f(x) about the base point x=a: >> clear, syms x; Tay_expx =taylor(exp(x),5,x,3) This is exactly correct only at x = 3. >> ezplot(Tay_expx), hold on, ezplot(exp(x)), hold off
Dsolve
r = dsolve('eq1,eq2,...', 'cond1,cond2,...', 'v') r = dsolve('eq1','eq2',...,'cond1','cond2',...,'v') symbolically solves the ordinary differential equation(s) specified by eq1, eq2,... using v as the independent variable and the boundary and/or initial condition(s) specified by cond1,cond2,....
5/6/2010
5/6/2010
Histograms
32
The plotting command plotyy allows one to plot two different data sets (with the same range in the dependent variable) on the same plot but with different scales for the -axes.
% Double y axes plot; Also demonstrate subplots x = -10:.1:10; % define points for independent variable y1 = (sin(x)./x).^2; % "dot" operator squares individual elements % and not the whole array y2 = 3*sin(abs(x)); subplot(2,1,1); % Divide figure into 1x2 array of plots and start with #1 plot(x,y1,x,y2); % Plot both data sets an same scale subplot(2,1,2); % Put next plot in second slot plotyy(x,y1,x,y2)
5/6/2010
creates histograms
hist
5/6/2010
5/6/2010
Polar Plots
34
Often when we are plotting data we can estimate the error in each point and the magnitude of error may vary from point to point. % Plotting with error bars
close all; clear all; x = linspace(0,pi,30); y = 1-x.^2/2+x.^4/(4*3*2); error = cos(x)-y; errorbar(x,y,error)
Example:
>>t = 0:.01:2*pi; >>polar(t,sin(2*t).*cos(2*t), '--r')
5/6/2010 5/6/2010
Stair Plots
36
5/6/2010
5/6/2010
5/6/2010
Stem Plot
38
5/6/2010
5/6/2010
Pie Plot
39
References
http://mathworks.com Lecture Notes of Aylin Konuklar and Lale Ergene
5/6/2010
10