Practical 7: Symbolic Toolbox

Site: learnonline
Course: MATLAB
Book: Practical 7: Symbolic Toolbox
Printed by: Guest user
Date: Saturday, 18 May 2024, 4:36 PM

Description

MATLAB Short Course

Practical 7

Symbolic Toolbox

  1. Be able to graph symbolic equations using ezplot
  2. Understand the advantages/disadvantages of the three types of graphingin MATLAB - plot, fplot, ezplot3
  3. Realise how numbers are represented with the Symbolic Toolbox
  4. Manipulate equations with algebraic operations
  5. Use the variable substitution & expression evaluation commands
  6. Perform symbolic differentiation and integration.

Working through this Practical

  • The exercises are indented and on separate pages with shaded areas. Do these!
  • Ask your MATLAB eTutor if you have any questions or need advice using the Practical's Forum
  • MATLAB code will always be denoted by the Courier font.
  • An arrow > at the start of the line in an exercise indicates an activity for you to complete.
  • Use the arrows on the top right and bottom right of this display to move between pages, or select a page using the left hand navigation pane.
  • You can also print this resource as a single document (using the print icon in 1.9 or the Admin section in 2.5/2.6).

Please submit your responses to the activities within this practical for formative feedback from your MATLAB eTutor. This word document template can be used to prepare your responses for submission.

The Symbolic Toolbox

The past practicals have introduced MATLAB as a powerful programmable graphics calculator. Now we will start showing you how, using MATLAB Symbolic Toolbox, you can, not only solve equations, but also perform algebraic manipulations, such as differential and integral calculus like finding the derivative f' \left(x\right) analytically.

 

> Exercise: Introducing the Symbolic Toolbox

> Type in the following commands.

clear all

sin(x)

>What error message is displayed?

The reason for this error message is that you have not first given x a value. However, if we make x a symbolic variable by using the syms x command, then we will be able to create and manipulate formulae without giving x a value first.

> Type in the following and see if you still get the same error message.

syms x

sin(x)

The syms command is actually a shortcut for the sym command. The longer way of writing is:

sym(‘x’)

> Exercise: Symbolic Variables

> Type in the following and decide which variables are symbolic.

syms x

y = x + 1.4*sqrt(x+3) + 5.49

pretty(y)

>What does the pretty command do here?

Solving Equations

The Symbolic Toolbox can be used to find solutions for single or simultaneous equations using the solve command.

Solving a Single Equation

The first task is to solve a single equation f \left(x\right)=0 for the variable x, with the result stored in the variable a. This can be done with command solve.

a = solve(f,x)

> Exercise: Using solve for a Single Equation

> Go through and type in the code for the following steps to solve the single equation.

 \frac{10}{x^{3}+1} =4-2x

> Watch out! There is an error that you will need to correct!!

1. Decide what f \left(x\right) is (you will need to rearrange the equation)

In this case

f(x)= \frac{10}{x^{3}+1} -4+2x

2. Create a symbolic variable x syms x
3. Create a symbolic variable f by assigning a symbolic expression to it f=10/(x^3+1)-4+2x
4. Solve f \left(x\right)=0 u = solve(f,x)

 

 

Example

 

> Exercise: Another Example of Solving Symbolic Equation

> Solve the general quadratic equation ax^{2}+bx+c=0 for any x by making the three coefficients a, b, c and x symbolic variables.

syms a b c x

> Instead of creating a new variable f for function, use the following command to solve directly:

soln = solve(a*x^2+b*x+c)

 

The above command doesn’t specify the variable to solve for. If it is not specified, the solve command will:

1) Solve for x by default or

2) Solve for the last alphabetical variable if there is no variable called x or

3) Solve for the only symbolic variable if there is only one.

> Exercise

> Solve the equation again, replacing a with u, b with v, c with w and x with s.

syms u v w s

...

> What is the answer this time?

Solving Simultaneous Equations

The solve command not only allows us to find solutions of single equations, but also simultaneous equations.

The command for solving more than one equation is of the form

[a1,a2,...,an] = solve(f1,f2,...,fn,v1,v2,...,vn)

This command can solve n equations for n unknowns.

> Exercise: Using solve for Simultaneous Equations

> Use MATLAB to find the solution of the following simultaneous equations:

2y+3x=4

5y-2x=5

> This time you will need to create two functions, f1 and f2 to solve f1=0 and f2=0 using the following command:

[x,y] = solve(f1,f2)

Graphing ezplot

The Symbolic Toolbox command ezplot is very convenient for plotting. You will need to specify the symbolic function and the endpoints (optional). By default, the endpoints are -2 \pi and 2 \pi.  Hence, you will need to determine endpoints only if they are different from the default ones.

Note: It is possible to plot several functions on the same graph using ezplot and hold on, hold off commands. But the graphs will have the same line properties (colour, thickness, etc) and thus sometimes are hard to distinguish.

> Exercise: Using the ezplot command

> Type the following code and examine output plots.

syms x

ezplot(sin(x))

ezplot(sin(x),[-pi pi])

hold on

ezplot(sin(x))

ezplot(3*x+2)

hold off

 

Plotting Functions

Table for Comparison of 3 Graph Plotting Functions

Command plot fplot ezplot
Required inputs
  • array of x- coordinates
  • array of y- coordinates
  • function handle
  • endpoints
  • symbolic function
  • endpoints
Advantages
does not need a function formula
full control of graph parameters
  • does not need a function formula
  • full control of graph parameters
  • function is stored in M-file for easy access (via handle) and modification
  • can easily create a graph using only two lines of code
Disadvantages
  • requires more code to generate
  • must create a function M-file if it is not MATLAB in-build function
  • function is not stored in easily accessible M-file,
  • graphs have the same colour

 

Example:

Create a graph of the function

Graph

 

Which plot command would you use?

Answer:

The answer depends on your overall task.

If you will need this function for further calculations, then use fplot command. To use fplot, you will need to create a function M-file, specifying the three parts of the function separately by using if statements.

If you want just to plot this function, then use ezplot with hold on and hold off commands to plot it ‘piece-by-piece’, specifying endpoints.

clear all

syms x

hold on

ezplot(x,[-2, 0])

ezplot(2*x,[0, 1])

ezplot(3*x,[1, 2])

axis([-2 2 -2 6])            %why do you need to do this?

title(‘Piece-wise function’) %what changes will happen if you delete this command?

hold off

wink Note: If you plot several functions using ezplot, then the title of the figure will be of the last function plotted. The hardest option for this sort of function is to use the plot command. Otherwise, all the above options are relatively same.

Quickly check that the equation speed=20ln(t+1) accurately reflects the speed of a car for t between 0 and 10 seconds.

Hint: use ezplot.

> Exercise: Graphing

> In the table below you are given the results of a student’s weekly assignments to plot.

> Which graphing technique would you use in this case?

Week 1 2 3 4 5 6 7 8 9 10 11 12
Grade 88 97 100 49 76 33 100 88 87 63 10 82

Evaluating Equations

You can find the value of an equation at a point using commands subs, eval.

> Exercise: Evaluating Equations

Consider the function f(x)=\left(x^{3}+2\right) \sec x

> Define this function f in the Symbolic Toolbox, by first defining x as a symbolic variable.

> Find f(0.157)  by evaluating this function at x = 0.157 using the subs command as follows:

y = subs(f,x,0.157)

> Find f(0.123) by evaluating this function at x=0.123 using the eval command as follows:

x = 0.123

y = eval(f)

As you can see the difference in these two examples is only in the number of commands you need to use to evaluate the function at a certain x.

 

Algebraic Transformation

The Symbolic Toolbox allows algebraic transformation of a function using the subs command

> Exercise: Variables’ substitution

> Type the following commands, where function f is the same as in the previous example.

syms t

y2=subs(f,x,t)     %substitutes x with t

y3=subs(f,x,t-1)    %substitutes x with t-1

y3=simple(y3)       %to simplify the expression for y3

> Exercise: subs Command

> Define function f(x)=x^{4}-5x^{2}+4 in the Symbolic Toolbox. Make sure that you typed syms x before the function’ definition. Substitute x with  \sqrt{t}  using subs command. Do not forget to type syms t before substitution.

Numbers

Let’s use the following example to illustrate the difference between symbolic and standard numbers representation.

> Exercise: Numbers

> Use the polynomial roots command to find the roots of the polynomial p \left(x\right)=x^{2}+9x+6

> Now, define x as a symbolic variable and define the polynomial p in MATLAB as follows:

p = x^2+9*x+6

> Use the solve(p) command to find the roots using the Symbolic Toolbox.

> What is the difference between the answers for the standard and symbolic methods?

 

Number Format

By default, the Symbolic Toolbox uses integers or rational fractions such as 1, 1/2.

Otherwise, it uses a real number approximation by a fraction of large integers, eg 3333/100000. Command sym(number) converts a number to its symbolic form while double(number) command reverses symbolic representation to MATLAB standard format. Therefore, sym command means ‘switch to Symbolic Toolbox’, while double means ‘switch back to MATLAB’

> Exercise: Understanding Numerical Formats

> For the following numbers, find out their symbolic and standard formats.

Number Symbolic Command Standard Command
11/13 sym 11/13 double (11/13)
3.85
pi
0.33333
(4/5)2 sym((4/5)^2 double ((4/5)^2)
591/2
e1
sin(1)

Algebraic Operations

A table of the most common Symbolic Toolbox Algebraic Operations

pretty Formats output to look like type-set mathematics
simplify Performs algebraic and other function simplifications
simple Tries a number of simplification techniques including trigonometric identities. Running this command twice can further simplify complex expression.
collect Collects like terms
factor Attempts to factor the expression
expand Expands all terms
poly2sym Converts an array of polynomial coefficients into a symbolic expression with x as the variable
sym2poly Converts symbolic polynomial into its coefficient array

 

 

> Exercise: Using Algebraic Operations

> Let p(x)=x^{2} \left(x+4\right)^{2}-8x \left(x+1\right)^{2}+13x-6

> Define p in a script M-file called symPoly.m using the following commands:

syms x

p = x^2*(x+4)^2-8*x*(x+1)^2+13*x-6

> Now use the algebraic operations to help you create the following five cells.

  1. Expand p
  2. Find the factors of p
  3. Store the coefficient array of p in a variable called coeff_p
  4. Use the solve command to find when p = 0
  5. Now try the polynomial roots command together with double to find the roots of p(x) in standard MATLAB format.

Differentiation and Integration

The Symbolic Toolbox features special commands for differentiation and integration. This practical will focus only on the basic diff and int commands. The default variable for integration or differentiation is x (first), or t (if there is no x) but you can specify another symbol.

> Exercise: Finding Derivatives & Integrals

> Open your script M-file symPoly.m with the equation p \left(x\right)=x^{2} \left(x+4\right)^{2}-8x \left(x+1\right)^{2}+13x-6.

> Create two new cells using the following commands to find the 1st and 2nd derivatives of p(x) as well as the indefinite and the definite integral from -1 to 1.

 

dp=diff(p,x)                 % note that you do not need to specify x because it is the default variable

d2p = diff(p,x,2)            % How would you find the third derivative of x?

intp = int(p,x)

intpDef=int(p,x,-1,1)

 

Numerical Integration

Sometimes there is no explicit expression because the antiderivative can’t be written in terms of familiar functions. Instead MATLAB can use numerical techniques to find the definite integral by using the double command.

> Exercise: Limitations of Integration Techniques

> Create a symbolic equation  f \left(v\right)= \frac{ \sin v}{v+e^{v}}

> Use the int command to find the indefinite integral, and observe the output.

intf = int(f,v)

> Modify the above command to find the definite integral between v=0 and v=pi.

Does the command work?

> Observe what happens if you use the double command.

defint=double(int(f,v,0,pi))

Toolbox Functions

sym(‘x’) or syms x Creates a symbolic variable x
sym(1/4) Creates symbolic number 1/4
double(1/4) Converts symbolic number 1/4 to standard 0.25
subs(f,x,a) Substitutes a variable x in f(x) with value a and finds f(x)

x=a

eval(f)

Finds value of f(x) at a by assigning a to x first.
ezplot(f,a,b) Plots the symbolic function f(x) over the interval [a,b]
pretty Formats output to look like type-set mathematics
simplify Performs algebraic and other function simplifications
simple Tries a number of simplification techniques including trigonometric identities. Running this command twice can further simplify complex expression.
collect Collects like terms
factor Attempts to factor the expression
expand Expands all terms
poly2sym Converts an array of polynomial coefficients into a symbolic expression with x as the variable
sym2poly Converts symbolic polynomial into its coefficient array
diff(f,x) Finds 1st derivative of f(x) with respect to x
diff(f,x,n) Finds nth derivative of f(x) with respect to x
int(f,x) Indefinite integral of f(x)
int(f,x,a,b)

Definite integral of f(x) with endpoints a , b

Questions?

You may also wish to discuss these questions within the Practical 7 forum, also embedded below. If you think you know the answer, you are welcome to respond.

 

Submit

Please submit your response to Practical 7 for feedback (also embedded below). Use this word document as a template.