matlab course math292 math391

33
INTRODUCTION TO MATLAB By Dr. Ahmad Salamah

Upload: hussein-dhaini

Post on 04-Dec-2015

239 views

Category:

Documents


2 download

DESCRIPTION

Matlab course

TRANSCRIPT

INTRODUCTION TO MATLAB

By

Dr. Ahmad Salamah

Contents

Overview on Matlab

Basic Matrix Operations

2D Plotting Commands

Important Symbolic Toolbox Commands

Revision Problems

Introductory Sessions on MATLAB

In this lab you will learn how to use MATLAB to create and operate on numeric and symbolic

variables but mainly on matrices. The commands needed to do this are short and easy to remember

MATLAB Environment

The main item in the MATLAB environment is the “MATLAB Command Window” . In this window,

the user is prompt to enter his commands. Commands are executed interactively, one by one. Another

important item is the “MATLAB Editor”, where the user can write a group of commands to be later

executed in batch mode. Other items include the “Workspace Window”, which lists a record of current

variables in use.

It is noteworthy that MATLAB is case sensitive, that is two variables I and i correspond to different

variables. Variable names must begin with a letter.

Facilities provided by MATLAB are grouped into Toolboxes, which offer advanced functions in a

specific field. For example, the MATLAB symbolic toolbox extends the computational power of

MATLAB to the manipulation of symbols.

Useful Commands

The following set of commands are simple useful commands:

(1) The help command: It is written as

>> help

(2) The clear console command: It is written as

>> clc

(3) The clear memory command: It is written as

>> clear

Useful Hint

The keyboard arrows may be used to move between previously written commands.

Numeric Variables

To define numeric variables just type the name of the variable and assign it its numeric value.

>> a = 9;

This command sets the value of the variable a to 9. However, no output is generated on the screen, this

is because of the semicolon at the end of the command.

>> a= 9

a =

9

Basic Operators

+ Addition

- Subtraction

* Multiplication

/ Division

^ Exponentiation

A′ Transpose of the matrix A

Precedence of Operators

To evaluate numeric expressions, MATLAB executes the mathematical operations in the order

indicated below:

1. Parentheses

2. Exponentiation

3. Multiplication and Divisions

4. Addition and Subtraction

MATLAB proceeds execution in a left to right order.

Example(1) >> (2*5)^2+9

ans =

109

Predefined Constants

Among the predefined constants in MATLAB are the values of π written as pi and the value of

1− written as i or j .

Built-in Functions

In what follows a list of some of the most commonly used arithmetic MATLAB built-in functions is

presented.

• sin(x), cos(x), tan(x) : return the sine, cosine and tangent of the angle x given in radians.

• asin(x), acos(x), atan(x) : represent the inverse trigonometric functions. The result is in radians.

• exp(x) : returns the value of xe

• log(x) : returns the value of xln

Matrix Variables

MATLAB is especially efficient in matrices manipulation. Matrix variables are defined as follows:

• A space or a comma separates the columns (the elements within a row)

• A semicolon separates rows.

Example(2)

For example, the matrix

−=

175

128

041

A is defined by using the following command:

>> A = [ 1 4 0; -8 2 1; 5 7 1];

Indexing Elements of a Matrix

To index the elements of a matrix, circular brackets are used instead of the square brackets, the row

no. followed by the column no.:

>> a = A(2,1)

a=

-8

The above command retrieves the element in matrix A located in the second row and the first

column.

Plotting Data Points

MATLAB has powerful visualization and graphical tools. One useful tool is the plot(x,y) function.

This function takes as input two vectors x and y of the same length representing the x- and y-

coordinates of a given set of data points, respectively. The data points are connected using straight

lines. To obtain smooth curves, a large data set is required.

Example(3)

Define the vectors representing the given data points, the use the function plot(x,y).

>> x = [ 1 2 3 4];

>> y= [1 4 9 16];

>> plot(x,y)

1.0 1.5 2.0 2.5 3.0 3.5 4.0

0

5

10

15

20

Among the plotting options supported by the plot(x,y) function is specifying a marker (*, +,…) and a

line style (solid, dotted,..). The marker as its name suggests marks data points. If a marker is specified

and no line style is set, then this is used to plot the data points with no connections.

>> plot(x,y,’*’)

1.0 1.5 2.0 2.5 3.0 3.5 4.0

0

5

10

15

20

Symbolic Variables

The symbolic toolbox enables MATLAB to manipulate symbols as well as numeric variables. To

define a set of symbolic variables the following command is used.

>> syms x y;

Hence, symbolic expressions may be defined in terms of these symbolic variables. Substitution of

symbolic variables, differentiation, evaluation of limits, evaluation of definite and indefinite integrals

and many other symbolic tools are supported in MATLAB. Consider the following example.

>> syms x;

>> y = x^3 + 1;

>> subs(y,x,3)

ans =

28

In the above example, the command subs(y,x,3) is used. The first argument is the expression. The

second argument is the variable to be substituted and the third argument is the value to be substituted

in the expression in place of the symbol.

Homework (1)

This session is a collection of exercises on the previous session.

1. Use MATLAB, to evaluate the following expressions.

2^3+4, sin(pi), 5/10^2+3, (2*3)^2*(6+7)

2. Define the matrices

−−

−=

415

210A and

−−=

520

131B , hence find the result of

2IBAAB tt++ after writing it in the corresponding MATLAB syntax.

3. Use MATLAB to plot the following set of data points in a scattered manner: (1,2), (2,4), (3,6),

(4,8).

4. Plot the set of points in the previous problem, but this time connected. Comment on the result.

5. Define the symbolic variable x and use a suitable command to evaluate the symbolically

defined expression xex sin at π=x

Basic Matrix Operations

The underlying data structure in MATLAB is a multi-dimensional array (e.g., scalar, vector, or

matrix). A column vector is an m-by-1 matrix, a row vector is a 1-by-n matrix and a scalar is a 1-by-1

matrix The mathematical operations defined on matrices are the subject of linear algebra.

(1) Entering Matrices

You can enter matrices into MATLAB in several different ways.

• Enter an explicit list of elements.

• Load matrices from external data files.

• Generate matrices using built-in functions.

• Create matrices with your own functions in M-files.

The following rules showed be followed when entering a matrix:

• Separate the elements of a row with blanks or commas.

• Use a semicolon, ; , or press Enter key to indicate the end of each row.

• Surround the entire list of elements with square brackets, [ ].

Examples

To enter a matrix by explicitly listing its elements, simply type:

>> A = [1 2 3; 4 5 6]

MATLAB displays the matrix you just entered, A =

1 2 3

4 5 6

To load matrices from external data files, type:

>> load <filename>

In the load command, you just specify the name of the data file to be loaded. Before using the load

command, use the save command to first create the data file.

MATLAB built-in functions could be used to generate some special matrices. The following list

includes useful ones.

• zeros(m,n): generates an nm × matrix with all its elements equal to zero. >> A=zeros(2,2)

A =

0 0

0 0

• ones(m,n): generates an nm × matrix with all its elements equal to one. >> B=ones(3,2)

B =

1 1

1 1

1 1

• The Identity Matrix: Generally accepted mathematical notation uses the capital letter I to

denote identity matrices, matrices of various sizes with ones on the main diagonal and zeros

elsewhere. These matrices have the property that AI = A and IA = A whenever the dimensions

are compatible. In MATLAB the function is eye(m,n), which returns an m-by-n rectangular

identity matrix and eye(n) returns an n-by-n square identity matrix.

>> C=eye(3)

C =

1 0 0

0 1 0

0 0 1

• Matlab has many types of matrices which are built into the system. An m-by-n matrix with

random entries is produced by typing rand(m,n)

>> r=rand(2,3)

r =

0.47 0.85 0.20

0.42 0.53 0.67

For more information on the rand(m,n) function, type:

>> help rand

(2) Addition and Subtraction

Addition and subtraction of matrices is defined just as it is for arrays, element-by-element. Addition

and subtraction require both matrices to have the same dimension, or one of them be a scalar. If the

dimensions are incompatible, an error results.

>> A=eye(2);

>> C=ones(3,2);

>> X = A + C

Error using ==> +

Matrix dimensions must agree.

>> v = [ 1 2 3; 0 9 8];

>> s = [ 0 9 2; 1 -9 7];

>> w = v + s

w =

1 11 5

1 0 15

Scalar Addition >> p = A + 2

p =

3 2

2 3

notice that adding a scalar number to a matrix, adds this number to each of the elements of the matrix.

(3) Matrix Multiplication

Multiplication of matrices is defined in a way that allows compact representation of systems of

simultaneous linear equations. The matrix product C = AB is defined when the column dimension of A

is equal to the row dimension of B, or when one of them is a scalar. If A is m-by-p and B is p-by-n,

their product C is m-by-n. MATLAB uses a single asterisk to denote matrix multiplication. A matrix

can be multiplied on the right by a column vector and on the left by a row vector. Rectangular matrix

multiplications must satisfy the dimension compatibility conditions. It is noteworthy that matrix

multiplication is not a commutative operation.

>> A = [ 1 5; 9 0];

>> C = [1 2 3; 7 0 -1];

>> X = A*C

X =

36 2 -2

9 18 27

>> Y = C*A

Error using ==> *

Inner matrix dimensions must agree.

Anything can be multiplied by a scalar.

>> s = 7;

>> w = s*A

w=

7 35

45 0

(4) Transpose Operation

For real matrices, the transpose operation interchanges aij and aji. MATLAB uses the apostrophe (or

single quote) to denote transpose

>> B = [ 8 1 6; 1 5 9; 6 7 2];

>> X = B'

X =

8 1 6

1 5 7

6 9 2

Transposition turns a row vector into a column vector. >> v = [ 2 0 -1];

x = v'

x =

2

0

-1

If x and y are both real column vectors, the product x*y is not defined, but the two products x’*y

and y’*x are the same scalar.

(6) Determinants and Matrix Inversion

If A is square and nonsingular, the equations AX = I and XA = I have the same solution, X. This

solution is called the inverse of A, which is denoted by 1A−

, and is computed by the function

inv(A). It is noteworthy that a matrix is non-singular if its determinant is non-zero. The function

det(A) computes the determinant of a square matrix A.

>> A = [1 1 1 ; 1 2 3; 1 3 6];

>> d = det(A)

d =

1

>> X = inv(A)

X =

3 —3 1

—3 5 —2

1 —2 1

(7) Matrix Powers

If A is a square matrix and p is a positive integer, then A^p multiplies A by itself p times.

>> A = [ 1 1 1 ; 1 2 3; 1 3 6];

>> X = A^2

X =

3 6 10

6 14 25

10 25 46

If A is square and nonsingular, then A^(–p) multiplies inv(A) by itself p times.

>> Y = A^(–3)

Y =

145 -207 81

-207 298 -117

(8) Solving a System of Linear Equations

First write the system of linear equations in matrix format: Ax=b where A is the coefficients matrix,

x is the vector of unknowns and b is the vector of free terms. When A is a square invertible, write

>> x = inv(A) * b

A quite faster command to solve a system of linear equations is:

>> x = A\B

(9) The Colon Operator

The colon, :, is one of MATLAB’s most important operators. It occurs in several different forms. For

example, the expression 1:10 is a row vector containing the integers from 1 to 10 >> x = 1 : 10

x =

1 2 3 4 5 6 7 8 9 10

To obtain non unit spacing, specify an increment. For example, the expression 100:–7:50 yields the

sequence (100, 93, 86, 79, 72, 65, 58, 51) and the expression 0:pi/4:pi yields the sequence (0, 0.7854,

1.5708, 2.3562, 3.1416).

(10) Subscripts and Indexing

The element in row i and column j of A is denoted by A(i,j). For example, A(2,4) is the number

in the second row and fourth column.

>> A = [ 1:2:7; 2:-1:-1]

A=

1 3 5 7

2 1 0 -1

>> b = A(2,4)

b=

-1

It is also possible to refer to the elements of a matrix with a single subscript, A(k). This is the usual

way of referencing row and column vectors. But it can also apply to a fully two-dimensional matrix, in

which case the array is regarded as one long column vector formed from the columns of the original

matrix. So, for our matrix A, A(5) is another way of referring to the value stored in A(1,3). If you try

to use the value of an element outside of the matrix, it results in an error.

>> t = A(4,5)

Index exceeds matrix dimensions.

Subscript expressions involving colons refer to portions of a matrix. A(1:k,j) is the first k elements

of the jth column of A. The colon by itself refers to all the elements in a row or column of a matrix

and the keyword

end refers to the last row or column.

>> A(:,end)

ans =

7

-1

Further examples to demonstrate how to access elements of a vector:

>>x(3) % 3rd element of the array

>>y(2:4) % 2nd till the 4th elements of the array

>>x(4:end) % starting from the 4th element of the array till the end

>>y(3:-1:1) % 3rd,2nd,1st element of the array

>>x(1:2:6) % 1st,3rd,5th element of the array

>>y([4 1 5 ])% 4th ,1st,5th element of the array in that order

Further examples to demonstrate how to access matrix elements:

>>A(1,[2 4])

ans =

3 7

(11) Deleting/ Altering Rows and Columns

You can delete rows and columns from a matrix using just a pair of square brackets. Start with

>> X = A;

Then, to delete the second column of X, use

>> X(:,2) = []

This changes X to

X =

1 5 7

2 0 -1

To change the second row in X, type:

>> X(2,:) = [ 2 5 7];

(12) Concatenation

Concatenation is the process of joining small matrices to make bigger ones. In fact, you made your

first matrix by concatenating its individual elements. The pair of square brackets, [], is the

concatenation operator. For example, consider the following operations.

>> r = [ 0 8 3 ; 9 7 4; 0 -1 -2];

>> b = [ 1 2 3]’;

>> s = [ r, b]

s =

0 8 3 1

9 7 4 2

0 -1 -2 3

>> q = [r ; b’]

q =

0 8 3

9 7 4

0 -1 -2

1 2 3

>> A=zeros(2,2);

>> B=ones(3,2);

>> C=[ [A;B], [B+5;A-7] ]

C =

0 0 6 6

0 0 6 6

1 1 6 6

1 1 -7 -7

1 1 -7 -7

(13) Element-by-Element Operations

Operators preceded by a dot (e.g. .^), refer to the fact that the operation is to be carried out element-

by-element. For example, >> A = [ 1:2:7; 2:-3:-7]

>> X = A.^2

X =

1 9 25 49

4 1 16 49

>> Y = 1./A

Y =

1 0.1111 0.04 0.0204

0.25 1 0.0625 0.0204

(14) Some Useful Built-in Array Functions

The following elementary arithmetic functions by default operate on individual matrix elements:

• Trigonometric functions. (e.g. sin(x), cos(x),..)

• The Exponential function (exp(x))

• The Logarithmic function (log(x),…)

• The square root function (sqrt(x))

and many others.

>> A = [ pi 0; pi/4 pi/3];

>> C = cos(A)

C =

-1 1

0.7071 0.5

>> B = [ 9 16 25, 1 4 9];

>> c = sqrt(B)

c =

3 4 5

1 2 3

The following set of functions operate on individual columns of a matrix:

• sum(M): returns the sum of individual columns in the matrix M in a row vector. If M is a

vector, it returns the sum of its elements.

• max(M): It returns the maximum element of the individual columns in the matrix M in a row

vector. If M is a vector, it returns the maximum of its elements

>> S = sum(B)

S=

10 20 34

The length(X) function returns the number of elements in the vector X, whereas the function size(M)

returns the number of rows and columns of the input matrix M, respectively.

>> [ m n] = size(B)

m =

2

n =

3

Homework (2)

This session is an exercise on the previous two sessions.

1) Given the following matrices: A=

86

21, B=

31

96, C=

25

39, D=

11

11, evaluate the

following expressions after writing them in MATLAB syntax:

a) 5A+B-3C

b) A 1−B + 1−C

c) At+5D

d) |A| |B| / |C|

e) Compare |A||B| and |AB|

2) Try entering the following matrices: the matrices

a) [eye(2);zeros(2)]

b) [eye(2);zeros(3)]

c) [eye(2),ones(2,3)]

Did any of the last three examples produce error messages? What is the problem?

3) Given A=[1 6 8 19 7;5 7 4 11 0;13 6 9 8 10;5 9 7 4 12;6 5 15 6 3 ]. Find its inverse and

calculate its determinant.

4) Enter the matrix A=

−− 21

21, find the inverse of A? what did you notice? find the determinant of

the matrix A? what is this matrix called?

5) Solve the systems of equations:

a) x1 + x2 = 2, x1 - x2 = 0

b) 2 x1 - x2 - x3 = 1, x1 + x2 + 2x3 = -4, 3 x1 - 3x2 -4x3 = 6

c) 3 x1- 2x2+ x3 = 1, x2 - 2x3 = 2, x1 + 0.5 x2 - 1.5 x3 = 2

6) Use MATLAB to evaluate the following functions at x=0, ππ ,2/ in one step:

a) cos(x)

b) x cos(x)

c) ex sinx

7) Enter a matrix A whose first row is 1 2 3 4 5 and the second row is the same numbers in a reverse

order using the “:” operator

8) Given x=[1 2 3] and y=[9 10 11]t , evaluate the sum of the corresponding elements of the x and y

vectors.

9) Given the matrix

−=

532

106M , write suitable MATLAB commands to construct the following

submatrices:

a) The first and last columns in the matrix M.

b) The last row of M.

c) Same as M, but replace the second column in M by the vector v = [ 1 -1]t

d) The first two elements in the first row in M.

e) Append the vector r = [ 4 5 0] to the matrix M as a last row.

10) Find the sum of all the elements in the matrix M in the previous problem using suitable MATLAB

commands. Find also the number of its elements.

11) Find the average of the following data values: x=7, y=10, z=15 using the sum command.

2D Plotting

MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as

annotating and printing these graphs. This session describes a few of the most important graphics

functions and provides examples of some typical applications. These functions will be used to aid you

visualize previously studied elementary functions in calculus as well as conic sections.

Creating a Plot

Two important graphics functions supported in MATLAB are the fplot and plot functions.

The fplot function is used to plot a single variable function in a specified range, as the following

example illustrates.

>>fplot(‘sin(x)’,[-pi,pi])

The result of executing this command is that the following figure appears in a separate figure

window.

As illustrated in the previous example, the first argument is the function we need to plot defined in

MATLAB syntax. The second argument is the range of the independent variable. The range for the

dependent variable may also be specified.

fplot has other optional arguments. The most important one is the plotting options argument. This

argument is a 1-, 2-, or 3-character string (delineated by single quotation marks) constructed from a

color, a linestyle, and a marker.

• Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'. These correspond to cyan, magenta, yellow,

red, green, blue, white, and black.

• Linestyle strings are '–' for solid, '– –' for dashed, ':' for dotted, '–.' For dash-dot, and 'none' for

no line.

• The most common marker types include '+', 'o', '*', and 'x'.

The plot function has different forms, depending on the input arguments:

1. If y is a vector, plot(y) produces a piecewise linear graph of the elements of y versus the index

of the elements of y.

2.If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x, that is, the

vector x includes the x-coordinates and the vector y includes the corresponding y-coordinates for the

points on the curve we plot.

In general, the plot function uses a straight line to join the points in the input vectors. Of course, to

draw a straight line it is sufficient to specify two points on it.

-2 0 2

-1

-0.5

0

0.5

1

1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0

-2.0

-1.5

-1.0

-0.5

0.0

0.5

1.0

1.5

2.0

2.5

3.0

To obtain smooth curves a large number of points is needed. For example, to plot the value of the

sine function from zero to 0 to π , type:

>>t=0:pi/100:2*pi; % a vector containing 200 points

>>y=sin(t);

>>plot(t,y)

0 1 2 3 4 5 6 7

-1.0

-0.8

-0.6

-0.4

-0.2

0.0

0.2

0.4

0.6

0.8

1.0

The plot function accepts a third optional argument which is a string specifying the color, line

style and marker to be used in the plot, just as that for the fplot function. For example, consider the

following the statements:

>> t=0:0.5:2*pi;

>> y=cos(t)

>> plot(t,y,':*')

The final statement plots the cosine function using a dotted line and places asterisk sign markers at

each data point, as the following figure illustrates.

0 1 2 3 4 5 6

-1.0

-0.8

-0.6

-0.4

-0.2

0.0

0.2

0.4

0.6

0.8

1.0

Notice that reducing the number of points in the vector t , by increasing the step size, produces less

smooth curves.

If you specify a marker type but not a line style, MATLAB draws only the marker. Consider the

following example.

>> x = [ 1 2 3 4];

>> y= [1 4 9 16];

>> plot(x,y,’*’)

1.0 1.5 2.0 2.5 3.0 3.5 4.0

0

5

10

15

20

But the statement >> plot(x,y,’*:’)

produces the following curve

1.0 1.5 2.0 2.5 3.0 3.5 4.0

0

5

10

15

20

Notice that the points in the vectors x, y belong to a parabola. Increasing the resolution of the above

plotting command, we obtain the standard curve of the parabola 2xy = , whose vertex is the origin.

>> x= -2:0.1:2;

>> y= x.^2;

>> plot(x,y,’*:’)

-2.0 -1.5 -1.0 -0.5 0.0 0.5 1.0 1.5 2.0

0.0

0.5

1.0

1.5

2.0

2.5

3.0

3.5

4.0

Controlling Axes

The axis function has a number of options for customizing the scaling, orientation, and aspect ratio

of plots. Ordinarily, MATLAB finds the maxima and minima of the data and chooses an appropriate

plot box and axes labeling. The axis function overrides the default by setting custom axis limits,

axis([xmin xmax ymin ymax]). The axis function also accepts a number of keywords for

axes control. For example,

• axis square: makes the entire x-axes and y-axes the same length

• axis equal: makes the individual tick mark increments on the x- and y-axes the same

length

• axis auto: returns the axis scaling to its default, automatic mode.

• axis on: turns on axis labeling and tick marks.

• axis off: turns off axis labeling and tick marks.

The statement grid on turns the grid lines on and grid off turns grid lines off.

Consider the following example of plotting a semicircle whose centre is the origin and radius equal

to 2.

>>theta=0:0.1:2*pi;

>> x= 2 * cos(theta);

>> y= 2 * sin(theta);

>>plot(x,y)

-2.0 -1.5 -1.0 -0.5 0.0 0.5 1.0 1.5 2.0

-2.0

-1.5

-1.0

-0.5

0.0

0.5

1.0

1.5

2.0

Here the circle appears somehow like an ellipse. Adding the command

>> axis square

-2 -1 0 1 2

-2.0

-1.5

-1.0

-0.5

0.0

0.5

1.0

1.5

2.0

It is clear that this option provides a better view for circular shapes.

Consider the following sequence of commands >>x=-2:0.1:2;

>>y=-x.^2;

>>plot(x,y)

>>grid on

the following curve is obtained

-2.0 -1.5 -1.0 -0.5 0.0 0.5 1.0 1.5 2.0

-4.0

-3.5

-3.0

-2.5

-2.0

-1.5

-1.0

-0.5

0.0

Again, the above curve is a parabola but this time it is inverted, oriented downwards.

Axis Labels and Titles

The xlabel, ylabel, and zlabel functions add x-, y-, and z-axis labels. The title function adds a title at

the top of the figure and the text function inserts text anywhere in the figure. A subset of Tex notation

produces Greek letters, mathematical symbols, and alternate fonts. The following example uses \leq

for ≤ , \pi for π , and \it for italic font.

>> t = –pi:pi/100:pi;

>> y = sin(t);

>> plot(t,y)

>> axis([–pi pi –1 1])

>> xlabel('–\pi \leq {\itt} \leq \pi')

>> ylabel('sin(t)')

>> title('Graph of the sine function')

>> text(1,–1/3,'\it{Note the odd symmetry.}')

It is noteworthy that editing the curve and axes properties may be done from within the figure

window.

Adding Plots to an Existing Graph

The hold command allows you to add plots to an existing graph. When you type hold on MATLAB

does not remove the existing graph; it adds the new data to the current graph, rescaling if necessary.

>> fplot(‘exp(-x)’,[ 0 3]);

>> hold on

>> fplot(‘exp(x)’,[-3 0]);

>> axis([-3 3 0 1]);

The hold on command causes the positive exponential function plot to be combined with the negative

exponential function plot in one figure.

-3 -2 -1 0 1 2 3

0.0

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1.0

It is worth mentioning that you should toggle the hold on flag when you finish up with the figure.

A useful command when dealing with multiple plots in one figure is the legend command. Legend

adds a box containing labels for the curves in the figure.

>> x=[0:0.2:2*pi];

>> y=sin(x);

>> plot(x,y,’b*-’)

>> hold on

>> z=cos(x);

>> plot(x,z,’ro:’)

>> grid on

>> legend('sin(x)','cos(x)')

Another way to create multiple plots in one figure. The command plot(x,y1,x,y2), plots x

versus y1 and x versus y2 on one set of axes. Notice, you must enter x twice, once for each plot. For

example, the following statements plot two related functions of x, each curve in a separate

distinguishing line style:

>> x=-1:0.1:1;

>> y=sinh(x);

>> y1=cosh(x);

>> plot(x,y,':',x,y1,'-')

>> axis square

-2.0 -1.5 -1.0 -0.5 0.0 0.5 1.0 1.5 2.0

-1.5

-1.0

-0.5

0.0

0.5

1.0

1.5

2.0

Subplots

The subplot function allows you to display multiple plots in the same window or print them on the

same piece of paper. Typing subplot(m,n,p)breaks the figure window into an m-by-n matrix of

small subplots and selects the pth

subplot for the current plot. The plots are numbered along first the

top row of the figure window, then the second row, and so on. Consider the following example.

>>x=-3:0.1:3;

>>y=exp(x);

>>y1=exp(-x);

>>y2=cosh(x);

>>subplot(1,2,1)

>>plot(x,y,’:’)

>>hold on

>>plot(x,y1,’-‘)

>>subplot(1,2,2)

>>plot(x,y2)

-3 -2 -1 0 1 2 3

0

5

10

15

20

25

-3 -2 -1 0 1 2 3

1

2

3

4

5

6

7

8

9

10

11

Figure Windows

The plot function automatically opens a new figure window if there are no figure windows already

on the screen. If a figure window exists, plot uses that window by default. To open a new figure

window and make it the current figure, type figure. To make an existing figure window the current

figure, type figure(n) where n is the number in the figure title bar. The results of subsequent graphics

commands are displayed in this window.

Other Useful Graphics Commands

You may find the following set of commands useful:

Function Used to

plot3 Create a graph for a 3D data representing a space curve

loglog Create a graph with logarithmic scales for both axes

semilogx Create a graph with logarithmic scale for the x axis only

semilogy Create a graph with logarithmic scale for the y axis only

plotyy Create a graph with y-tick labels on the left and right side

gtext Position text using the mouse

clf Clears the figure

ginput Gather data by clicking on points in the plot

Homework (3)

1-Plot the square whose sides are x= -1, x= 1, y= -1 and y =1.

2-Plot the circle whose centre is the point (-1,1) and radius equal to 1. Use suitable axes options.

3- Plot the parabola defined by the equation x2

- 6x - 4y + 1= 0 in the interval [-4,8]. Identify its

vertex. Mark it on the figure. Add a grid for better visualization.

4-Plot the following data set as scattered points

x 0 2 3 5

y 3 1 –1 –2

On the same figure, plot the line x038.1846.2 − in the interval [0,5]. Add labels to both axes as

well as a title to the figure.

5-Plot the ellipse whose centre is the origin, major axis length is 4 and minor axis length is 2.

6-Plot both sin2x and sinx in the interval ]2,0[ π in one figure. Use distinguishing colors and line

styles. Add a legend. (Try using a single plot command).

7-Plot x1sin− and x

1cos− in the interval ]1,1[− as two adjacent subplots.

8-Plot the graph of the function xexf x sin)( −= in the interval ],[ ππ− . Try using both the fplot and

plot commands.

Symbolic Math Toolbox

The symbolic math toolbox supplements MATLAB numeric and graphical facilities with several other

types of mathematical computation, some of which are summarized in following table.

Facility Covers

Calculus Differentiation, integration, limits, summation and Taylor

series

Linear Algebra Inverses, determinants, eigen values

Simplification Methods of simplifying algebraic expressions

Solution of Equations Symbolic and numerical solutions to algebraic and

differential equations

Symbolic Objects

The Symbolic Math Toolbox defines a new MATLAB data type called a symbolic object. The

Symbolic Math Toolbox uses symbolic objects to represent symbolic variables, expressions, and

matrices. The following example illustrates the difference between a standard MATLAB data type,

such as double, and the corresponding symbolic object. The MATLAB command sqrt(2)returns a

floating-point decimal number: 1.4142. On the other hand, if you convert 2 to a symbolic object using

the sym command, and then take its square root by entering a = sqrt(sym(2))the result is a

=2^(1/2). MATLAB gives the result 2^(1/2), which means 21/2

, using symbolic notation for

the square root operation, without actually calculating a numerical value. You can always obtain the

numerical value of a symbolic object with the double command: double(a) which returns the

numeric value 1.4142

When you create a fraction involving symbolic objects, MATLAB records the numerator and

denominator. For example: >> sym(2)/sym(5)

ans =

2/5

MATLAB performs arithmetic on symbolic objects differently than it does on standard data types. If

you add two fractions that are of data type double, MATLAB gives the answer as a decimal fraction.

For example: >> 2/5 + 1/3

ans =

0.7333

If you add the same fractions as symbolic objects, MATLAB finds their common denominator and

combines them by the usual procedure for adding rational numbers: >> sym(2)/sym(5) + sym(1)/sym(3)

ans =

11/15

Creating Symbolic Variables and Expressions

The sym command lets you construct symbolic variables and expressions. For example, the

commands >> x = sym('x');

>> a = sym('alpha');

create a symbolic variable x that prints as x and a symbolic variable a that prints as alpha. To create

multiple symbolic variables, for example the symbolic variables (a,b,c,x), use the syms

command. >>syms a b c x;

To create a symbolic expression, consider the following sequence of commands as an example. >> syms x y z;

>> r = sqrt(x^2 + y^2 + z^2);

>> t = atan(y/x);

>> f = sin(x*y)/(x*y);

which generates the symbolic expressions r, t, and f. You can use diff, int, subs, and other

Symbolic Math Toolbox functions to manipulate such expressions.

The following example illustrates how to define a rational function. To create the function, enter the

following commands: >> syms x

>> num = 3*x^2 + 6*x -1;

>> denom = x^2 + x - 3;

>> f = num/denom

This returns f =

(3*x^2+6*x-1)/(x^2+x-3)

To create a symbolic expression that is a constant, you must use the sym command. For example, to

create the expression whose value is 5, enter f = sym('5'). Note that the command f = 5

does not define f as a symbolic expression.

If you set a variable equal to a symbolic expression, and then apply the syms command to the

variable, MATLAB removes the previously defined expression from the variable. For example, >> syms a b

>> f = a + b

returns f =

a + b

If you then enter >> syms f

>> f

MATLAB returns f =

f

Now suppose you want to study the quadratic function ax2+bx+c= 0. One approach is to enter

the command f = sym('a*x^2 + b*x + c')

which assigns the symbolic expression ax2+bx+c= 0 to the variable f. However, in this case, the

Symbolic Math Toolbox does not create variables corresponding to the terms of the expression

a,b,c,x. To perform symbolic math operations (e.g., integration, differentiation, substitution, etc.)

on f, you need to create the variables explicitly. A better alternative is to enter the command >>syms a b c x

Then enter f = sym('a*x^2 + b*x + c')

Simplifying Symbolic Expressions

The simplify function is a powerful, general purpose tool that applies a number of algebraic

identities involving sums, integral powers, square roots and other fractional powers, as well as a

number of functional identities involving trigonometric functions, exponential and logarithmic

functions .Here are some examples. >> syms x;

>> f=x*(x*(x-6)+11)-6;

>> simplify(f)

ans=

x^3-6*x^2+11*x-6

>> f=(1-x^2)/(1-x);

>> simplify(f)

ans=

x+1

>> syms x y;

>> f=exp(x)*exp(y);

>> simplify(f)

ans=

exp(x+y)

There are several functions that simplify symbolic expressions other than the simplify function.

Here are three different symbolic expressions. >> syms x

>> f = x^3-6*x^2+11*x-6

>> g = (x-1)*(x-2)*(x-3)

>> h = -6+(11+(-6+x)*x)*x

These expressions are three different representations of the same mathematical function, a cubic

polynomial in x. The Symbolic Math toolbox provides several functions, other than simplify, that

apply various algebraic and trigonometric identities to transform one representation of a function into

another, possibly simpler, representation. These functions include collect, expand, and factor.

If f is a polynomial with rational coefficients, the statement factor(f) expresses f as a product

of polynomials of lower degree with rational coefficients. If f cannot be factored over the rational

numbers, the result is f itself. Here are several examples.

>> factor(f)

ans=

(x-1)*(x-2)*(x-3)

>> factor(x^3-6*x^2+11*x-5)

ans=

x^3-6*x^2+11*x-5

>> factor(x^6+1)

ans=

(x^2+1)*(x^4-x^2+1)

Substitution of Symbolic Variables by Numeric Values

You can substitute a numerical value for a symbolic variable using the subs command. For

example, to substitute the value x = 2 in the symbolic expression,

>> f = 2*x^2 - 3*x + 1

enter the command >> subs(f,2)

This returns f(2):

ans =

3

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);

enter the command subs(f, x, 3)

This returns ans =

9*y+15*y^(1/2)

On the other hand, to substitute y = 3, enter >> subs(f, y, 3)

ans =

3*x^2+5*x*3^(1/2)

If you do not specify a variable to substitute for, MATLAB chooses a default variable according to

the following rule. For one-letter variables, MATLAB chooses the letter closest to x in the alphabet. If

there are two letters equally close to x, MATLAB chooses the one that comes later in the alphabet. In

the preceding function, subs(f,3) returns the same answer as subs(f,x,3).

Basic Calculus Built-in Symbolic Math Toolbox Functions

The Symbolic Math Toolbox provides functions to do the basic operations of

calculus. In what follows some of these functions are described.

(1) Differentiation

To illustrate how to take derivatives using the Symbolic Math Toolbox, first create a symbolic

expression: >> syms x

>> f = sin(5*x)

The command >> diff(f)

differentiates f with respect to x:

ans =

5*cos(5*x)

As another example, let >> g = exp(x)*cos(x)

and differentiate g:

>> diff(g)

ans =

exp(x)*cos(x)-exp(x)*sin(x)

To take the second derivative of g, enter >> diff(g,2)

ans =

-2*exp(x)*sin(x)

You can get the same result by taking the derivative twice: >> diff(diff(g))

ans =

-2*exp(x)*sin(x)

In this example, MATLAB automatically simplifies the answer. However, in some cases, MATLAB

might not simply an answer, in which case you can use the simplify command. Note that to take

the derivative of a constant, you must first define the constant as a symbolic expression. For example,

entering

>> c = sym('5');

>> diff(c)

returns ans =

0

If you just enter >> diff(5)

MATLAB returns ans =

[]

because 5 is not a symbolic expression.

(2) Integration

If f is a symbolic expression, then int(f)attempts to find another symbolic expression, F, so that

diff(F) = f. That is, int(f) returns the indefinite integral or antiderivative of f (provided one

exists in closed form). Similar to differentiation, int(f,v)uses the symbolic object v as the variable

of integration, rather than the variable determined by findsym. Definite integration is also possible.

The commands int(f,a,b)and int(f,v,a,b)are used to find a symbolic expression for

∫b

a

dxxf )( and ∫b

a

dvvf )( , respectively. See how int works by looking at this table.

Mathematical Operation MATLAB Command

∫+

=

+

1

1

n

xdxx

nn

int(x^n) or int(x^n,x)

12sin

2/

0

=∫π

dxx int(sin(2*x),0,pi/2)

abatdttg

batg

/)sin()(

)cos(

+=

+=

g=cos(a*t+b)

int(g) or int(g,t)

2ln1

2

1

=∫ dxx

int(1/x,1,2)

9/4ln

1

0

−=∫ dxxx

int(log(x)*sqrt(x),0,1)

Partial Fractions Decomposition

A nice trick to find the partial fraction decomposition of a rational function is to use

diff(int(f(x)). The following example illustrates the idea. >> syms s;

>> num = 3*s-1;

>> den = (s+1)*(s+2);

>> diff(int(num/den))

ans=

-4/(s+1)+7/(s+2)

Solving Algebraic Equations

The solve(eqn1,eqn2,...) command solves a system of equations in symbolic variables x1,

x2, ... . If s is a symbolic expression, solve(s) attempts to find values of the symbolic variable in

s (as determined by findsym) for which s is zero. For example, >> syms a b c x

>> s = a*x^2 + b*x + c;

>> solve(s)

uses the familiar quadratic formula to produce

ans =

[1/2/a*(-b+(b^2-4*a*c)^(1/2))]

[1/2/a*(-b-(b^2-4*a*c)^(1/2))]

This is a symbolic vector whose elements are the two solutions. If you want to solve for a specific

variable, you must specify that variable as an additional argument. For example, if you want to solve s

for b, use the command

>> b = solve(s,b)

which returns b =

-(a*x^2+c)/x

Note that these examples assume equations of the form f(x)=0. If you need to solve equations of

the form f(x)=q(x), you must use quoted strings. In particular, the command >> s = solve('cos(2*x)+sin(x)=1')

returns a vector with four solutions. s =

[ 0]

[ pi]

[ 1/6*pi]

[ 5/6*pi]

Homework (4)

1- Differentiate the following function three times: xxxf ln)( = and evaluate it at 1=x .

2- Differentiate the following function once: xxf 1tan)( −= and evaluate it at 1=x . Put the result in

rational format.

3-Evaluate the following integrals using MATLAB:

∫− x

dx

9, ∫

−29 x

dx and ∫

+

2/

0cos1

cosπ

dxx

x

4- Solve the following equations using MATLAB:

(i) 022=−− xx (ii) 1sin2cos =+ xx

5- Find the partial fractions decomposition for : 342

+− xx

x

6- Factorize the following polynomials:

(i) 1222 234+−+− xxxx (ii) 13

+x

0.0 0.2 0.4 0.6 0.8 1.0 1.2 1.4 1.6 1.8 2.0

-4

-3

-2

-1

0

1

2

3

4

Revision problems

Homework (5)

1- For the matrix

45

21, find:

a- its transpose

b- its determinant

c- add 2 to all its elements

d- replace its second row by [0 -1]

e- multiply it by its transpose

2- Using built-in functions generate the following matrices:

1000

0100

0010

0001

1111

,

2000

0200

0020

3- Solve the following system of linear equations:

x – y + z = 3, x + 3y + z = –1, x – 3z = –2.

4- Given the vectors: ]0321[ −=x and ]1652[=y , find ∑ ix , ∑ 2ix , ∑ ii yx .

5- Use suitable MATLAB commands to generate the following figures

Figure 1

y = x2

y= - x2

Figure 2

-1.5 -1.0 -0.5 0.0 0.5 1.0 1.5

-0.5

0.0

0.5

1.0

1.5

2.0

Figure 3

6- Factorize the following polynomial: 14−x

7- Evaluate the first derivative for 3sin)( += xxxf at 2/π=x

8- Find the partial fraction decomposition of )2)(1(

13

++

xx

x