Você está na página 1de 54

Experiment No.

1:

INTRODUCTION TO MATLAB

OBJECTIVES
1. Become familiar with the basic windows of MATLAB and their functions
and operations.
2. Perform scalar operations using MATLAB

INTRODUCTION
Matrix Laboratory - MATLAB
A high-level language for technical computing.
It integrates computation, visualization, and programming in an easy-to-use
environment where problems and solutions are expressed in familiar
mathematical notation.
Stands for matrix laboratory

MATLAB Windows
Command Window
Use to enter variables and run functions and M-files.
Command History
Statements you enter in the Command Window are logged in the
Command History. In the Command History, you can view previously run
statements, and copy and execute selected statements.
Workspace Browser
The MATLAB workspace consists of the set of variables (named arrays)
built up during a MATLAB session and stored in memory. You add
variables to the workspace by using functions, running M-files, and
loading saved workspaces.
Current Directory Window
Use to view files and subdirectories under a main directory.
Editor/Debugger Window
Use for writing and editing functions and programs.

Figure Window
The Figure Window opens automatically when graphics commands are
executed, and contains graphs created by these commands.

Assignment Operator ( = )
Variable_name = A numerical value, or a computable
expression

Variables
A variable in MATLAB may be in the form of a scalar quantity, vector
quantity, or a matrix.
MATLAB does not require any type of variable declarations or dimension
statements. When MATLAB encounters a new variable name, it
automatically creates the variable and allocates the appropriate amount of
storage. The variable list can be found in workspace window. If the
variable already exists, MATLAB changes its contents and, if necessary,
allocates new storage.
Eg.

>> xnum = 23;

Rules in Creating Variables


Can be up to 63 (in MATLAB 6.5) characters long (31 characters in
MATLAB 6.0).
Can contain letters, digits, and the underscore character.
Must begin with a letter.
MATLAB is case sensitive; For example, AA, Aa, aA, and aa are the
names of four different variables.
Avoid using the names of built-in function for a variable (i.e. avoid using:
cos, sin, exp, sqrt, etc.). Once a function name is used to
define a variable, the function cannot be used.

Predefined Variables
ans

A variable that has the value of the last expression that was
not assigned to a specific variable. If the user does not
assign the value of an expression to a variable, MATLAB
automatically stores the result in ans.

pi

The number .

eps

The smallest difference between two numbers.


Equals 2^(-52), which is approximately 2.2204e-016.

inf

Used for infinity.

Square root of -1, which is: 0 + 1.0000i.

Same as i.

NaN

Stands for Not-a-Number. Used when MATLAB cannot


determine a valid numeric value. For example 0/0.

realmax largest positive floating point number i.e. 1.7977e+308


realmin smallest positive floating point number i.e. 2.2251e-308.

Numbers
MATLAB uses conventional decimal notation, with an optional decimal
point and leading plus or minus sign, for numbers. Scientific notation uses
the letter e to specify a power-of-ten scale factor. Imaginary numbers use
either i or j as a suffix.

Eg.

5, -88, 0.0001, 3.63938, 1.23410e-20,


6.02252e23, 3i, 4.23j

All numbers are stored internally using the long format specified by the
IEEE floating-point standard. Floating-point numbers have a finite
precision of roughly 16 significant decimal digits and a finite range of
roughly 10-308 to 10+308

Arithmetic Scalar Operators


Expressions use familiar arithmetic operators and precedence rules.
+

Addition

Subtraction

Multiplication

Division

Power (exponentiation)

( )

Specify evaluation order

To define a scalar quantity


>> a = 2;

the variable a is a scalar with a value of 2 (1-by-1 matrix)

>> b = 1;
>> y = a^2+(b/3)-1

Built-in Math Functions


Function

Description

sin(x) Sine of angle x (x in

Example
>> sin(pi/6)
ans = 0.5000

radians).
cos(x) Cosine of angle x (x in

>> cos(pi/6)
ans = 0.8660

radians).

tan(x) Tangent of angle x (x in >> tan(pi/6)


ans = 0.5774

radians).

cot(x) Cotangent of angle x (x >> cot(pi/6)


ans = 1.7321

in radians).

Function
sqrt(x)

Description

Example

Square root.

>> sqrt(81)
ans = 9

exp(x)

Exponential (ex).

>> exp(5)
ans = 148.4132

abs(x)

Absolute value.

>> abs(-24)
ans = 24

log(x)

log10(x)

Natural logarithm.

>> log(1000)

Base e logarithm (ln).

ans = 6.9078

Base 10 logarithm.

>> log10(1000)
ans = 3.0000

factorial(x)

The factorial function x!

>> factorial(5)

(x must be a positive integer.) ans = 120

Display Format
Command
format short

Description

Example

Fixed-point with 4 decimal >> 290/7


ans =

digits

41.4286
format long

Fixed-point with 14 decimal >> 290/7


ans =

digits

41.42857142857143
format short e

Scientific notation with 4 >> 290/7


ans =

decimal digits.

4.1429e+001
format long e

Scientific notation with 15 >> 290/7


ans =

decimal digits.

4.142857142857143e+001
format rat

>> 290/7

Rational form

ans = 290/7

EXERCISES

A. Convert the following arithmetic expressions to MATLAB expressions that evaluate


to the same value.

1.

12 + 15
(3)(3)

2. 16 +
3. 1 +

4.

1
1 1
+
8 4

sin 30 o + cos 25 o
tan 30 o
5

5.

44
4
11

456 + 3 323
cos 80 o

B. Evaluate the following mathematical expressions using the command window

1. V =

4
R3 ,
3

2. y = ln(e 2 x +3 + x) ,

3.

for R = 2 meters
for x = 1.5

sin ( / 3) + cos( / 4)
in rational form
tan( / 6)

Experiment No. 2:

VECTOR AND MATRIX OPERATIONS

OBJECTIVES

1. To be able to perform basic vector arithmetic operations using MATLAB


2. To be able to perform basic matrix operations using MATLAB

INTRODUCTION

In linear algebra, vector is defined as an m-by-1 or 1-by-n array of elements


where m > 1 and n > 1 while matrix is defined as any m-by-n array of
elements where m > 1 and n > 1

To define a vector quantity, x and y


>> x = [1 2 3]

the variable B is a row vector (1-by-3 matrix)

x = 1 2 3

>> y = [1; 2; 3] the variable C is a column vector (3-by-1 matrix)

1
y =2
3

To define a vector quantity using colon operator

>> x1 = [0:2:10]
>> y1 = [0:2:10]

To define a vector quantity using linspace( ) function

>> x2 = linspace(0,10,5)
>> y2 = linspace(0,10,5)

To define a matrix, A which is a 3-by-3 matrix:

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

1 2 3
A = 4 5 6
7 8 9

Generating Arrays using the built-in functions of MATLAB


SYNTAX

eye (n)

DESCRIPTION

Creates an n-by-n identity matrix

ones (m,n)

Creates an m-by-n matrix all elements have value of 1

rand (m,n)

Creates an m-by-n matrix all elements of which are of


uniformly distributed random values ranging from 0 to 1

zeros(m,n)

Creates an m-by-n matrix all elements have value of zero

randn(m,n)

Creates an m-by-n matrix all elements of which are of


normally distributed random values with zero mean and
variance of 1

Vector and Array Addressing

Vector
>> v = [1 2 3 6 7 8]
>> v4 = v(4)
>> v6 = v(6)

Matrix
>> E = [1 2 3;4 5 6;7 8 9]
1 2 3
E= 4 5 6
7 8 9

>> e23 = E(2,3)


>> e32 = E(3,2)

Using a Colon
a. Vector
v(:) refers to all elements of the vector v
v(m:n) refers to elements m through n of the vector v
if v = 1 2 3 6 7 8

then v(2:5) = 2 3 6 7

b. Matrix
A(:,n) - Returns the elements of all the rows in column n of

matrix A.
A(n,:) - Returns the elements of all the columns in row n of

matrix A.
A(:,m:n) - Returns the elements of all the rows from column m

to column n of matrix A.
A(m:n,:) - Returns the elements of all the columns from row m

to row n of matrix A.
A(m:n,p:q) - Returns the elements from row m to row n and

from column p to column q of matrix A

2. Addition and Subtraction of Vectors and Arrays

Addition and subtraction require both vectors and both matrices to have
the same dimension, or one of them must be a scalar. If the dimensions are
incompatible, an error results.
Example 1:
>> v1 = [1 2 3 4 5];
>> v2 = [1 1 1 1 1];
>> vx = v1 + v2
>> vy = v1 v2

Example 2:
>> A = [1 2 3;1 0 1;-1 1 2];
>> B = [1 1 1; 1 1 -1;0 0 1];

>> C = A + B
>> D = A B

3. Multiplication of Vectors

a. Dot product / Scalar product


Also known as inner product
Produced by multiplying a row vector to a column vector
The result is a scalar quantity
b. Outer product
Produced by multiplying a column vector to a row vector
The result is a matrix

4. Multiplication of Matrix

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
Matrix multiplication is not commutative.

5.

Transpose of a Matrix

The transpose operation interchanges aij and aji


MATLAB uses apostrophe (or single quote) to denote transpose

6. Array Operations

Element-by-element operations
>> a = [1 2 3];
>> b = [1 2 3];

a. Multiplication
>> c = a.*b

10

b. Division
>> c = a./b

c. Exponentiation
>> c = a.^b

EXERCISES

For the following exercises, write a simple program in the MATLAB command window
and execute your program.

1. Let x = [2 4 6 8 10] and y = [1 3 5 7 9]. Compute for vector z whose elements


are equal to

xy +
z=

( x + y)

y
x
( yx)

+ 10 x / y

Create matrix C:

2 4 6 8 10
C = 3 6 9 12 15
7 14 21 28 35

Using array addressing, use matrix C to:


a. Create a three-element column vector named col_a that contains the
elements of the third column of C.
b. Create a five-element column vector named col_b that contains the
elements of the second row of C.
c. Create a 2x3 matrix named mat_B from the first and 2nd rows, and the
2nd , 3rd and 4th columns of the matrix C.

11

2. Generate the following matrices:

Matrix X
1 6 2
3 9 6

4 0 3

Matrix Y
1 9 4
2 0 5

1 7 3

Matrix Z
3 7 4
2 3 1

9 2 5

Determine the following:

a. transpose of X
b. matrix X added to matrix Z
c. matrix Y subtracted from matrix Z
d. matrix X multiplied by matrix Y
e. matrix X element-by-element multiplied by matrix Y
f. matrix Y divided by matrix Z
g. matrix Y element-by-element divided by matrix Z.

12

Experiment No. 3

SCRIPT FILES

OBJECTIVES

1. To be able to create simple programs under MATLAB environment.


2. To be able to perform basic MATLAB operations using M-files.

INTRODUCTION

SCRIPT FILES

A script file is a sequence of MATLAB commands it is also called a


program.
A script file is also known as M file because the extension .m is used when
they are saved.
A script file is created and edited in the Editor/Debugger Window.
Before a script file can be executed it has to be saved.
A script can be executed either by typing its name in the command
window and pressing Enter key, or directly from the Editor/Debugger
Window by clicking on the Run icon.

Input to a Script File

When a script file is executed the variables that are used in the calculations within
the file must have assigned values. There are three possible ways to assign a value
to a variable.
1. The variable is defined and assigned value in the script file

The assignment of value to the variable is part of the script file.


2. The variable is defined and assigned value in the command window.

The assignment of a value to the variable is done in the command


window.
3. The variable is defined in the script file, but a specific value is entered in
the command window when the script file is executed.

13

The variable is defined in the script file and when the file is executed, the
user is prompted to assign a value to the variable in the command window.
It uses the input() command.
Syntax:
variable_name = input(message string) or
variable_name = input(message string,s)

when the variable is assigned to be a string.

Output Commands
The disp() command

is used to display the elements of a variable without displaying the name


of the variable
Syntax: disp(variable_name)

or

disp(text as string)

The fprintf() command

is used to display output on the screen or to save it to a file.


It is also used to format the output
It is also used to save output to a file
Syntax: fprintf(text as string %5.2f additional
text,variable_name)

Where:

% : marks the spot where the number is inserted within the

text.

5 : field width (optional) specifies minimum number of


digits

2 : precision (optional) number of digits to the right of


decimal point

f : conversion character (required)

14

EXERCISES

1. Create a script file that will accept a value in metric unit (mass in kgs, and volume
cubic meter) and will output the equivalent density in lb/cu.ft.

2. Create a script file that will accept a volume (V), and a height (h) of a right
circular cone and will display the radius (r) of the base of the cone and the surface
area (S).
V=

1 2
r h
3

S = r r 2 + h 2

3. Write a script file that will compute the sin of an angle using the Taylor series
formula: sin x =

(1) k x 2 k +1
The program will prompt the user to input the

k = 0 ( 2 k + 1)!
n

angle x in degrees, and n the number of terms in the series. Use the program to
calculate sin(150o) using 5 and 9 terms.

4. Write a script file that determines the angles of a triangle when the lengths of the
sides are given. The program will prompt the user to enter the sides of the triangle

a, b, and c and the program will display the internal angles A, B, and C of
the triangle in degrees. Use the function to determine the angles in triangles with
the following sides.

a. a = 10, b = 15, c = 7
b. a = 6, b = 8, c = 10
c. a = 200, b = 75, c = 250

15

Experiment No. 4

FUNCTION FILES

OBJECTIVES

1. To be able to create functions or subroutines under MATLAB environment.


2. To be able to perform basic MATLAB operations using M-files.

INTRODUCTION

FUNCTION FILES

A function file is also known as a subroutine a special program which


has a specific function. Eg. sin(), sqrt(), atan()
It is a subprogram within a computer program.
A function file is also an M-file because the extension .m is used when
they are saved.
A function file is created and edited also in the Editor/Debugger Window.

Structure of Function File


1. Function Definition Line

It is the first executable line which defines the file as a function file and
not a script file.
Absence of function definition line means that the file is a script file.
It defines the function name.
It defines the number and order of the input and output arguments.
General Form:

function [output arguments] = function_name


(input arguments)

16

2. H1 Line and Help Text Lines (Optional)

Are the comment lines (lines that begins with % sign) following the
function definition line.
Provides information about the function
H1 line is the first comment line usually contains the function name and
a short definition of the function.
Help text lines are comment lines that follow the H1 line. It contains
explanations of the function regarding with the input and output
arguments.
The H1 line and help text lines are displayed in the command window
when the user typed

>> help function_name

3. Function Body

Contains the computer program that actually performs the computations.

Local Variables

Variables inside a function file and do not recognize in the command window.

Comparison between Function File and Script files

Both Script and Function files are saved with extension name .m
The first line in the function file is the function definition line
The variables in the function files are local. The variables in the script file are
recognized in the command window.
Script files can use variables that have been defined in the workspace.

17

EXERCISES

1. Create a function file that will accept a value in metric unit (mass in kgs, and
volume cubic meter) and will output the equivalent density in lb/cu.ft. For the
function name and arguments use:
D = density(M,V)

where D is the density, M is the mass and V is the volume.

2. Create a script file that will accept a volume (V), and a height (h) of a right
circular cone and will display the radius (r) of the base of the cone and the surface
area (S). For the function name and arguments use:
[r,S] = radius_area(h,V)

where r is the radius, S is the surface area, h is the height and V is the volume.

V=

1 2
r h
3

S = r r 2 + h 2

3. The function sin(x) can be written as a Taylor series expanded form i.e.:

( 1) k x 2 k +1
sin x =
Write a user defined function file that calculates sin(x)
k = 0 ( 2 k + 1)!
by using the Taylor series. For the function name and arguments use:
y = my_sin(x,n). The input arguments are the angle x in degrees, and n the

number of terms in the series. Use the function to calculate sin(150o) using 5
and 9 terms and compare the result by using the built-in function y = sin(x).

4. Write a user-defined MATLAB function that determines the angles of a triangle


when the lengths of the sides are given. For the function name and arguments use
[A,B,C] = triangle(a,b,c). Use the function to determine the angles in

triangles with the following sides.


a. a = 10, b = 15, c = 7
b. a = 6, b = 8, c = 10
c. a = 200, b = 75, c = 250

18

Experiment No. 5:

MATLAB PROGRAMMING

OBJECTIVE

1. To become familiar with the programming environment of MATLAB.


2. To apply programming skills in MATLAB.

INTRODUCTION

PROGRAMMING in MATLAB

Relational Operators

Relational Operator

Description

<

Less than

>

Greater than

<=

Less than or equal to

>=

Greater than or equal to

= =

Equal to

~ =

Not equal to

Logical Operators

Logical Operator

Description

&

AND

OR

NOT

xor(A,B)

Exclusive or

19

Order of Precedence

Precedence

Operation

1 (highest)

Parentheses ( )

Exponentiation

Logical NOT (~)

Multiplication, Division

Addition, Subtraction

Relational Operators

Logical AND (&)

8 (lowest)

Logical OR ( | )

Built-in Logical Functions

Function

Description

and(A,B)

Equivalent to A & B

or(A,B)

Equivalent to A | B

not(A)

Equivalent to ~ A

xor(A,B)

Exclusive or. Returns true if one operand


is true and the other is false.

all(A)

Returns true if all elements in a vector A


are true. Returns false if one or more
elements are false.

any(A)

Returns true if any element in a vector A


is true. Returns false if all elements are
false.

find(A)

If A is a vector, returns the indices of the


nonzero elements.

find(A>b)

If A is a vector, returns the address of the


elements that are larger than b.

20

Logical Operators
INPUT

OUTPUT

AND

OR

XOR

NOT A

NOT B

Conditional Statements
1. The if-end Structure
3. The if-elseif-else-end Structure

if conditional expression
if conditional expression 1

command 1
command 2

command 1

command 2

command n

end

command n

elseif conditional
expression2

2. The if-else-end Structure

command 1
command 2

if conditional expression
command 1

command 2

command n

else

command 1

command n

command 2

else
command 1

command 2

command n

end

command n

end

21

The switch-case Statement

Provides a means for choosing one group of commands for execution out of
several possible groups.
switch switch expression

command 1

case value 1

:
command n

command 1
:

otherwise%optional

command n

case value 2

command 1
:

command 1

command n

end

command n

case value 3

Loop Commands

1. for-end Loop

for k = i:s:f
command 1
:
command n

end

where:

i initial value
s interval or interval
f final value

22

2. while-end Loop

while conditional expression


command 1
:
command n

end

23

EXERCISES

1. Write a program in a script file that determines the real roots of a quadratic
equation ax 2 + bx + c = 0 . Name the file quadroots. When the file runs it
asks the user to enter the values of the constants a, b, and c. To calculate
the roots of the equation the program calculates the discriminant D given by:
D = b 2 4ac

If D > 0 the program displays a message: The equation has two roots, and
the roots are displayed in the next line.
If D = 0 the program displays a message: The equation has one root, and
the root is displayed in the next line.
If D < 0 the program displays a message: The equation has no real roots
Run the program using the following equations:
a. 2 x 2 + 8 x 3 = 0
b. 15 x 2 + 10 x + 5 = 0
c. 18 x 2 + 12 x + 2 = 0
2. The function f ( x) = e x can be represented in a Taylor series by:

xn
e =
Write a program in a script file that determines ex by using the
n = 0 n!
x

Taylor series representation. The program calculates ex by adding terms of the


series and stopping when the absolute value of the term that was added last is
smaller than 0.0001. Use a while-end loop, but limit the number of passes to
30. If in the 30th pass the value of the term that is added is not smaller than
0.0001, the program stops and displays a message that more than 30 terms are
needed. Use the program to calculate e2, e4, and e21.
3. Create a function file that accepts a vector of any length and return a vector
whose elements are arranged in descending order. For the function name and
arguments use b = downsort(a) where a is the input vector and b is the
output vector. Do not use the MATLAB built-in sort function.

24

Experiment No. 6:

TWO-DIMENSIONAL (2-D) PLOTS

OBJECTIVES

1. To be able to generate two-dimensional plots using MATLAB


2. To be able to visualize graphically common functions in y = f(x) form

INTRODUCTION

1. Plot

The basic plotting function accepts character-string arguments that specify


various line styles, marker symbols, and colors for each vector plotted. In
the general form
plot(x,y,line style_marker_color)

where x horizontal axis (vector)

y vertical axis (vector)


x and y must have the same length

Line Specifiers
Used to define the style and color of the line and the type of
markers.

Line Style

Specifier

Solid (default)

Dashed

--

Dotted

Dash-dot

-.

25

Line Color

Specifier

Red

Green

Blue (default)

Cyan

Magenta

Yellow

Black

White

Marker Type

Plus sign

Circle

Asterisk

Point

Square

Diamond

Five-pointed star

Six-pointed star

Property Name

linewidth

markersize

Specifier

Description

Property Value

Specifies the width of the

A number in units of points

line

(default 0.5)

Specifies the size of the

A number in units of points

marker

26

markeredgecolor Specifies the color of the


marker, or the color of the

Color specifiers from the


table above, typed as a string

edge line for filled markers

markerfacecolor Specifies the color of the


filling for filled markers

Color specifiers from the


table above, typed as a string

Example:

Creates a plot that connects the points with a solid line(-), color magenta (m) and
circle (o) as markers at the points. The line width is 2 points and the size of the
circle markers is 12 points. The markers have a green (g) edge line and yellow (y)
filling.

>> x = [0:0.5:5];
>> y = 2.^x+1;
>> plot(x,y,mo,linewidth,2,markersize,12,
markeredgecolor,g,markerfacecolor,y)

Useful commands

1. stem(x,y) - Plots discrete sequence data

2. hold on - it retains the current plot and its properties and allows the user

to plot additional graphs on the same figure window.

3. line(x,y) adds the line in vectors x and y to the current axes.

4. xlabel(text) adds label on the horizontal axis of the current graph

5. ylabel(text) adds label on the vertical axis of the current graph

27

6. title(text) adds title on the current graph

7. legend(text1,text2,) puts a legend on the current plot

8. grid on adds grid on the current plot

9. semilogx(x,y) plots y versus x with a log (base 10) scale for the y axis

10. semilogy(x,y) plots y versus x with a log (base 10) scale for the x axis

11. loglog(x,y) plots y versus x with a log (base 10) scale for both axes

12. bar(x,y) vertical bar plot

13. barh(x,y) horizontal bar plot

14. pie(x) pie plot, where x is a row vector which specifies the division of

pie.

15. hist(y) histogram, where y is a row vector.

16. polar(theta,radius) polar plot, where theta and radius are vectors.

17. subplot(m,n,p) plots multiple graphs on the same page with a number

of mxn plots with size of m rows and n columns at position p.

28

EXERCISES

Answer or simulate the following problems. Write the command that you used and draw
all the graphs generated:
1. Plot the function f ( x) =

x2 x +1
for 10 < x < 10
x2 + x +1

2. Plot the following functions using polar plot in a single plot using the following
conditions
a. r = 1 + 2 sin , for 0 < < 6 . Use red dash-dot line for the plot.
b. r = 1 2 sin , for 0 < < 6 . Use black solid line for the plot.
c. r = 1 + 2 cos , for 0 < < 6 . Use green dash-dot line for the plot.
d. r = 1 2 cos , for 0 < < 6 . Use yellow solid line for the plot.

3. An electrical circuit that includes a voltage source E with an internal resistance r,


and a load resistance R is shown in the figure. Plot the power P as a function of R
for 1 < R < 10 given that E = 12V and r = 2.5. Prove that maximum power
transfer will occur when the internal resistance, r and load resistance R are equal.

4. Given the function y = e 10 x for 0 < x < 20 , compare the graphs using the
function plot() and using log scale plot.

29

Experiment No. 7:

THREE DIMENSIONAL (3-D) PLOTS

OBJECTIVE

1. To be able to present data in graphical form consisting of more than two


independent variables

INTRODUCTION

3-D Line-Plot

A line that is obtained by connecting points in a 3-D space.


Syntax:
plot3(x,y,z,line specifiers,PropertyName
,property value)

x, y and z vectors of the coordinates of the points. (must have the


same number of elements)

Example

>> t = 0:0.1:6*pi;
>> x = sqrt(t).*sin(2*t);
>> y = sqrt(t).*cos(2*t);
>> z = 0.5*t;
>> plot3(x,y,z,k,linewidth,1)
>> grid on
>> xlabel(x); ylabel(y); zlabel(z)

3-D Mesh and Surface Plots

Used for plotting functions of the form Z = f(X,Y) where the X and Y are
the independent variables and Z is the dependent variable.

30

Steps:
1. Creating a grid in the x-y plane
[X,Y] = meshgrid(x,y)

X is the matrix of the x coordinates of the grid points.


Y is the matrix of the y coordinates of the grid points.
x is the vector that divides the domain of x.
y is the vector that divides the domain of y.

2. Calculating the value of z at each point of the grid.

Z is calculated using element-by-element calculations.


Z = f(X,Y) note that the matrix X and Y must be of the same size.

3. Making mesh and surface plots


Once the three matrices exist (X,Y and Z), they can be used to plot mesh or
surface plots.
Syntax:
mesh(X,Y,Z) or surf(X,Y,Z)

X,Y are matrices with the coordinates of the grid and Z is a matrix with

the value of z at the grid points.

Other Mesh and Surface Plot Commands


meshz(X,Y,Z)

mesh curtain plot

meshc(X,Y,Z)

mesh and contour plot

surfc(X,Y,Z)

surface and contour plot

surfl(X,Y,Z)

surface plot with lighting

waterfall(X,Y,Z)

waterfall plot draws a mesh in one direction

only

31

contour3(X,Y,Z,n)

3-D contour plot n is the number of contour

levels (optional)
2-D contour plot n is the number of contour

contour(X,Y,Z,n)

levels (optional)

EXERCISES

Answer or simulate the following problems. Write the command that you used and draw
all the graphs generated:

1. Plot the function z = 10 0.8

x2 + y2

sin( x) for 2 < x < 2 and 2 < y < 2 . Use the

following commands and compare each plot

a. mesh(X,Y,Z)
b. meshz(X,Y,Z)
c. meshc(X,Y,Z)
d. surf(X,Y,Z)
e. surfc(X,Y,Z)
f. surfl(X,Y,Z)
g. waterfall(X,Y,Z)
h. contour3(X,Y,Z,50)
i. contour(X,Y,Z,50)
2. Plot the following functions in 3D using plot3 command for 5 < t < 5

x = e at sin w t
y = e at cos w t
z = e bt

32

a. Use a = 0.2 , b = 0.2 and w = 5


b. Use a = 0.5 , b = 0.2 and w = 5
c. Use a = 0.2 , b = 0.2 and w = 10
d. Use a = 0.2 , b = 0.7 and w = 5

Compare all the generated graphs from one to another and explain the effects
of changing a, b, and w

33

Experiment No. 8:

POLYNOMIAL OPERATIONS

OBJECTIVE

1. To be familiar with different elementary polynomial operations of


MATLAB
2. To be able to solve mathematical problems involving polynomials using
MATLAB

INTRODUCTION

Polynomials
Polynomials are functions that have the form:

f ( x ) = a n x n + a n 1 x n 1 + .... + a 1 x + a 0
Examples are:

X ( z) = 5z 5 + 6z 2 + 7 z + 3
H ( z ) = 2 z 2 4 z + 10

The representations of these polynomials in MATLAB are:


p = [5 0 0 6 7 3]
q = [2 -4 10]

Useful Commands:

polyval(p,x) evaluates the value of a polynomial for a given value of x

o p is a vector with the coefficients of the polynomial.


o x is a number, or a variable that has an assigned value.

conv(h,x) performs multiplication of two polynomial functions h and x

34

[q,r] = deconv(u,v) performs division of two polynomial

functions where
o u numerator polynomial
o v denominator polynomial
o q quotient polynomial
o r remainder polynomial

roots(p) computes for the roots of the polynomial equation p

poly(r) generates the polynomial expansion given the roots r

[r,p,k] = residue(b,a) computes the partial fraction expanded

form of a given rational polynomial function b and a

o b numerator polynomial
o a denominator polynomial
o r coefficients of partial fraction expanded form
o p roots (factors) of the polynomial a
o k direct term coefficient when the degree of b is greater than or

equal to the degree of a

ARITHMETIC OPERATIONS OF POLYNOMIALS

Addition / Subtraction of Polynomials

Two polynomials can be added (or subtracted) by adding the vectors of the
coefficients.
If the polynomials are not of the same order, the shorter vector has to be
modified to be of the same length as the longer vector by adding zeros in
front (called padding)

35

Examples: solve f1(x) + f2(x)


f 1 ( x) = 3x 6 + 15 x 4 2 x 3 + 2 x 1
f 2 ( x) = x 4 + 5 x 3 + x 2 2 x + 3

Multiplication of Polynomials

Syntax:

c = conv(a,b)

c is a vector of the coefficients of the polynomial that is the product of

the multiplication.
a,b are the vectors of the coefficients of the polynomials that are being

multiplied.

Examples: solve f1(x) . f2(x)


f1 ( x) = x 3 2 x 2 + 2 x 1
f 2 ( x) = x 2 + 3

Division of Polynomials

A polynomial can be divided by another polynomial using the command deconv


command.
Syntax: [q,r] = deconv(u,v)
Where:q is a vector with the coefficients of the quotient polynomial.
r is a vector with the coefficients of the remainder polynomial.
u is a vector with the coefficients of the numerator polynomial.
v is a vector with coefficients of the denominator polynomial.

Example:

a. Divide 2x3 + 9x2 + 7x 6 by x + 3

36

Derivative of Polynomials

k = polyder(p)

o derivative of a single polynomial, p. k is a vector with the coefficients of

the polynomial that is the derivative.

k = polyder(a,b)

derivative of a product of two polynomials a and b.

[n,d] = polyder(u,v)

o derivative of a quotient of two polynomials.

Curve fitting with Polynomials

Also known as regression analysis


A process of fitting a function to a set of data points.

Syntax:

p = polyfit(x,y,n)

p is the vector of the coefficients of the polynomial that fits the data.
x is a vector with horizontal coordinate of the data points (independent

variable)
y is a vector with the vertical coordinate of the data points.
n is the degree of the polynomial

37

EXERCISES

Answer or simulate the following problems. Write the command that you used and draw
all the graphs generated:

1. Solve the roots of the equation:


a. 3x2 + 8x + 5 = 0
b. 5x2 + 7x + 7 = 0
c. 5x3 + 7x2 7x + 8 = 0

2. Find the polynomial expression given the following factors:

a. (x + 3) (x 2) (x + 2) (x + 4)
b. (x + 2) (x 7) (x + 1) (x + 2)

3. Expand using partial fraction expansion

Q( s) =

3s + 2
( s 3)( s + 2)( s 5)

4. Solve for the


a. roots of numerator,
b. polynomial form of the denominator
c. partial fraction expanded form of the given system functions

a. H ( z ) =

3z 3 + 2 z 2 z + 2
( z 3)( z + 2)( z 5)( z 2)

b. H ( z ) =

3z 5 + 2 z 3 z 2 + 2
4z 4 2z 2 + 3

38

5. Given a set of data points x and y, estimate three polynomial functions (2nd
degree, 3rd degree and 4th degree) that will best fit the data. Compute new set of y
data from the three functions and determine which of the three functions will give
the least norm difference.

norm =

v1 + v 2 + v3 + ... + v n
2

x = [0.9, 1.5, 3, 4, 6, 8, 9.5]

y = [0.9, 1.5, 2.5, 5.1, 4.5, 4.9, 6.3]

39

where v n = y n y new n

Experiment No. 9:

MATLAB GUI Part 1

OBJECTIVES
1. Become familiar with the basic graphic user interface commands and operation of
MATLAB.
2. Build basic MATLAB-based graphic user interface.

INTRODUCTION
Graphic User Interface GUI

A graphical user interface is a pictorial interface to a program.


Advantages of using GUI
1. It makes things simple for the end users.
2. Users would not have to work from the command line interface.
3. Makes a program easy to understand.

Properties of a good GUI


1. Must be user friendly and easy to use.
2. Should behave in an understandable and predictable manner.
3. Must be simple and neat.
4. Must be functionally accurate.

Three principal elements required to create a MATLAB GUI


1. Components Items in MATLAB GUI like push buttons, labels, edit boxes, etc. is a
graphical component.

There are four types of components;


a. Graphical controls push buttons, edit boxes, sliders etc. Created by function
uicontrol.
b. Static elements text strings, frames. Created by function uicontrol.
c. Menus created by function uimenu and uicontextmenu.
d. Axes used to display graphical data. Created by function axes.

2. Figures A window in the computer screen where all components of the GUI must
be arranged.

40

3. Callbacks Code executed in response to an event such as mouse click or a key


press.

Basic GUI Components (figure 9.1)


Graphical controls
1. Pushbutton triggers a callback when clicked by a mouse.

2. Toggle button either on or off, it changes state each time it is clicked, each
click triggers a callback.

3. Radio button a type of toggle button that appears as a small circle with a dot, a
group of radio buttons are used to implement mutually exclusive
choices. Each click triggers a callback.

4. Check box a type of toggle button that appears as a small box with a check
mark. Each click triggers a callback.

5. Edit box displays a text string and allows the user to modify the information
displayed. A callback is triggered when the user presses the
Enter key.

6. List box displays a series of text strings which a user can select one of the text
strings. A callback is triggered when the user selects a string.

7. Pop-up menu displays a series of text strings in response to a mouse click.


When a pop-up menu is not clicked on, only the currently
selected string is visible.

41

8. Slider adjusts a value in a smooth, continuous fashion by dragging the control


with a mouse. Each slider change triggers a callback.

Figure 9.1

Static elements
1. Frame creates a frame, a rectangular box within a figure. Used to group sets of
controls together. Never triggers callbacks.
2. Text Field creates a label, a text string located at a point on the figure. Never
triggers callbacks.

Menus and Axes


1. Menu items creates menu item. Trigger callback when a mouse button is
release over them.

42

2. Context menus creates a context menu, which appears over a graphical object
when a user right-click the mouse on that object.
3. Axes creates a new set of axes to display data on. Never triggers callbacks.

GUI Development Environment

MATLAB GUI are created using the GUI Development Environment or simply
called guide, see figure 9.2. In using guide, MATLAB allows the programmer
to do the following;
1. Layout the GUI.
2. Select and align GUI components.
3. Edit GUI components properties.
4. Create a working program to implement the behavior of the GUI, referred to as the
GUI M-File.

Figure 9.2

GUI M-File

After laying out your GUI, you can program the GUI M-file using the M-file
editor. GUIDE automatically generates this file from your layout the first time
you save or run the GUI.
The GUI M-file does the following;

43

1. Initializes the GUI.


2. Contains code to perform tasks before the GUI appears on the screen,
such as creating data or graphics.
3. Contains the callback functions that are executed each time a user
clicks a GUI component.

Steps in creating GUI


1. Decide what elements are required by the GUI, what the function of each element
will be.
2. Type guide in the MATLAB command window.
3. Visually design the GUI interface.
4. Use the GUI Development Environment tool Property Inspector to give each
component a name and to set characteristics of each component such as color, text
display and so on.
5. Save the figure to a file. When the figure is saved, two files will be created on disk
with the same name but different extensions. The .fig contains the actual GUI and the
M-file contains the code.
6. Add the code to implement the behavior associated with each callback function.

Figure 9.3

44

Figure 9.4

Properties for GUI Components

Name Property The value of a figure's Name property is the title that displays at the
top of the GUI. The first time you save or run the GUI, GUIDE sets the value of Name to
the name of the FIG-file. Once the GUI is saved, you can set the value of Name to the
string you want to use as its title. In the field next to Name, type Simple GUI, as shown in
the following figure.

Figure 9.5

Title Property A panel's Title property controls the title that appears at the top or
bottom of the panel. Select the panel in the Layout Editor and then scroll down in the
Property Inspector until you come to Title. In the field to the right of Title, change Panel
to Plot Types. Use the TitlePosition property to control the position of the title.

45

Figure 9.6

String Property You can set the label in some user interface controls, such as push
buttons and static text, by using the String property. For example, to set the label of the
top push button, select the push button in the Layout Editor and then, in the Property
Inspector, scroll down until you come to String. In the field to the right of String, change
Push Button to Surf, as shown in the following figure.

Figure 9.7

Tag Property The Tag property provides a string as a unique identifier for each
component. GUIDE uses this identifier to construct unique callback names for the
different components in the GUI. When you first add a component to a layout, GUIDE
sets the value of Tag to a default string such as pushbutton1. If the component has a
Callback property, GUIDE also sets the value of Callback to the string %automatic.

46

Figure 9.8

The GUI M-File Editing


In the GUI M-File you add code to the callbacks for the three push buttons and the popup menu. Once GUIDE has created the M-file, you can open it in the MATLAB editor by
clicking the M-file Editor icon on the toolbar. In the editor, you can move the cursor to a
specific callback by clicking the function icon on the toolbar, then selecting the callback
you want in the pop-up menu that displays.

Figure 9.9

47

For example, clicking MyFirstGUI_OpeningFcn moves the cursor to the opening


function. The next topic explains how you can add code to the opening function to create
data for the GUI or perform other tasks.

SAMPLE PROGRAM
1. Type guide in the command line interface.
2. Layout the components in the GUI similar to figure 9.3 in order to achieve GUI in
figure 9.4.
3. Edit the properties of the components using Properties Inspector and follow the
settings as given below;

String

Click Here

Tag

MyFirstButton

String

Total Clicks: 0

Tag

MyFirstText

Name

My First GUI

Pushbutton

Static Text

Figure

4. Save as MyFirstGUI. MyFirstGUI.m and MyFirstGUI.fig will be created.


5. Go back to the command user interface, type MyFirstGUI then enter.
6. Open MyFirstGUI.m.
7. Implement callback function to MyFirstButton. By adding the code below.

48

Figure 9.10

Figure 9.10

EXERCISES

1. Improve MyFirstGUI, such that there will be two buttons, ADD and MINUS. The
ADD button when clicked will add 1; while the Subtract button when clicked will
subtract 1 from its current count value.

2. Add a Toggle Button to MyFirstGUI, such that the ADD and SUBTRACT buttons
can now be enabled and disabled.

3. Change the appearance of MyFirstGUI by changing its color, size, font and visual
settings.

49

Experiment No. 10:

MATLAB GUI Part 2

OBJECTIVES
1. Become familiar with the other graphic user interface commands and operation of
MATLAB.
2. Build basic calculator using graphic user interface.

INTRODUCTION
In this experiment you will be ask to create your own basic Calculator using MATLAD
graphic user interface development environment. The calculator must be similar to figure
10.1

Figure 10.1

Figure 10.2

50

In order to achieve proper vertical and horizontal alignment, you can use the Align
Objects tool. You can assign the proper alignment horizontally and vertically with
different types of distribution.

The MyFirstCalc.m code

Figure 10.3

51

In figure 10.3 you can verify that the Tag used for each push button as they
correspond to each callback. The other property settings are in table 10.1.

Table 10.1: Property Settings

String

Number or Math Operator Symbol

Tag

Button*

String

*No change

Tag

text1

Pushbuttons

Background Color

White (or your choice of


background color)

Static Text

Figure

Foreground Color

Black (or your choice of font color)

Font Size

30

Horizontal Alignment

Right

Name

My First Calc

Callback code for every pushbutton except the = (equals)

Figure 10.4

52

Callback code for the equal sign

Figure 10.5

After coding the callbacks for pushbuttons


The code for each pushbutton callback except the equals button is in figure 10.4, you
must edit it correspondingly to every pushbutton digit including the /, *, - and + operator
symbols. Figure 10.5 shows the one for the equals button callback. After completion, run
the GUI and you will be able to display numbers to the static textbox as shown in figure
10.6.

Figure 10.6

53

EXERCISES

1. Construct a basic calculator using MATLAB graphic user interface development


environment, using the settings indicated in the steps above.

2. Customize the calculator by adding a decimal point and clear button.

3. Add more pushbuttons such as (, ), sin, cos and tan, then create a callbacks for
each pushbuttons. Verify the operation of the calculator.

54

Você também pode gostar