Matlab Basics
Matlab Basics
NaN (obtained as a result of the mathematically undefined
operations, such as,
0
0
, or )
i,j
1
nargin Number of function input arguments used
margout Number of function output arguments used
eps Floating point precision
11
NOTE
Special variables can be assigned any value but when MATLAB is restarted or after
execution of clear command, the original values are restored.
Practice
-Build-in Functions & Predefined Variables-
(1)
Use MATLAB to evaluate the following expressions:
1. (7+3)=5 <enter>
2. (9-5)*6 <enter>
3. 3*cos(3*pi/4) <enter>
4. 3^2 <enter>
5. sqrt(5) <enter>
6. exp(5) <enter>
7. log(exp(2)) <enter>
8. 15/2 <enter>
9. 2\15 <enter>
10. atan(pi/4) <enter>
11. log10(100) <enter>
12. 3+sqrt(7) <enter>
Practice
-Build-in Functions & Predefined Variables-
(2)
Evaluate the following expression:
3
5 c rA B
>>c=2.3; r=5.1; A=3.4; B=1.5;
>>c^3-sqrt(r*A)-5*B <enter>
12
A list of functions designed for rounding numbers to integers is given below:
SYMBOL MEANING
floor(x) Largest integer less than or equal to x
ceil(x) Smallest integer greater than or equal to x
round(x) Round x to the closet integer
fix(x) Round x towards zero
To illustrate differences between these functions, let us consider the following
example:
Practice
-Rounding to Integers-
(1)
>>x=[-1.7 -0.3 3.6 5.8 7.2];
>>ceil(x)
ans =
-1 0 4 6 8
>>floor(x)
ans =
-2 -1 3 5 7
>>fix(x)
ans =
-1 0 3 5 7
>>round(x)
ans =
-2 0 4 6 7
13
Practice
-Rounding to Integers-
(2)
1. What is the integer closest to 173 ?
>>x=sqrt(173); <enter>
>>round(x) <enter>
2. Between what consecutive integers does
( )
5
2
1 + lie?
>>x=(pi^2+1)^5; <enter>
>>lbound=floor(x) <enter>
>>ubound=ceil(x) <enter>
answer: lbound<x<ubound
It is often the case in computer engineering to convert numbers from one base to
another. MATLAB has a number of functions tailored for that purpose. These
functions are bin3dec, dec2bin, hex2dec, dec2hex, dec2base, and oct2dec. Table
below provides a summary of these functions.
Function Meaning
dec2bin Convert decimal to a binary string
bin2dec Convert binary string to decimal integer
dec2hex Convert decimal to hexadecimal
hex2dec Convert hexadecimal to decimal
dec2base Convert dec numbers to octal numbers
oct2dec
hex2bin
Convert octal numbers to decimal numbers
Convert hexadecimal strings to binary strings
14
Practice
-Base Conversions-
Make the following base conversions:
1. ( )
8
723542 to decimal
>>oct2dec(723542)
ans: 239458
3. ( )
16
4 52 E B to binary
>>dec2bin(hexdec(4E52B)
ans: 1342453
5. ( )
2
1001011 to decimal
>>bin2dec(1001011)
ans: 75
2. ( )
10
8451 to binary
>>dec2bin(8451)
ans:10000100000011
4. ( )
16
5 52 C B to octal
>>dec2base(hex2dec(5C52B),8)
ans =1342453
-Commands You Have to Know-
Basic commands
The who command lists all the variables currently in workspace, and the whos
command list the variables in workspace and gives extra information regarding
memory allocation, class of the variables in memory, and size in bytes. Entering the
clear command without arguments removes all the variables in the current workspace
and clear followed by the name of any variable deletes only that variable in workspace
leaving other ones intact. The clc command clears the command window and resets
the command prompt at the top of the screen.
15
Practice
-Commands & Help-
(1)
>> x=1;
>> y=3;
>> d=[1 2; 4 5];
>> whos
Name Size Bytes Class
ans 1x5 40 double array
d 2x2 32 double array
x 1x1 8 double array
y 1x1 8 double array
Grand total is 11 elements using 88 bytes
Practice
-Commands & Help-
(2)
1. Use MATLAB to find the area of a circle of radius equal to 3.5.
>>%Evaluation of the area of a circle
>>radius=3.5; <enter> % set radius to 3.5
>>area=pi*r^2 <enter> % compute the area of the circle
2. Create three variables x, y, and z, then use the who, and whos commands to display
the variables in workspace. Afterwards clear all the variables and the MATLAB
command window.
>>x=2*cos(pi/6); <enter> % define variable x
>>y=5*sin(pi/4); <enter> % define variable y
>>z=exp(pi*sqrt(23)) <enter> % define variable z
>>who <enter> % display the list of variables in workspace
>> whos<enter> % give the list of variables with additional attributes
>>clear x <enter> % clear variable x
>>clear <enter> % clear all remaining variables
>>clc <enter> % clear command line window
16
NOTE
If a statement does not fit in the 80 spaces available on a line, you can split it over two
(or more) lines by placing an ellipsis (three periods) at the end of the line and resume
typing on the next line.
>>x=sin(2*pi*3*t)+2*sin(2*pi*6*t)+7*sin(2*pi*9*t)+
3*sin(2*pi*12*t);
On-screen Help
One of the nice features of MATLAB is its help system. There are many sources of
help in MATLAB. During any MATLAB session, online help is available for a
variety of topics. If you know the name of the command you want help on, you can
use the MATLAB help command followed by the name of the command to determine
its syntax.
>>help command name <enter>
>>help sin <enter> % provide the syntax for the sine function
A. lookfor Command
If you are unsure about the spelling or existence of a command, you can try to find it
using the lookfor command. The lookfor command searches the MATLAB files and
returns the names containing a specific keyword.
>>lookfor hilbert <enter> % retrieve all commands containing the keyword Hilbert
B. help Command
As soon as the command name is found, use the help command to retrieve its syntax.
If you type help with no parameters a list of main MATLAB topics appear on the
screen, while help topic_name returns all available commands on the specified topic.
>>help <enter> % return a list of the main MATLAB topics
>>help signal <enter> % return a list of functions of the signal processing toolbox
17
Row Vector
A straightforward way to generate a row vector is to list its elements, surrounded by
square brackets [ ]. Either commas or blanks may separate the elements of a vector.
For example, to create a vector having as elements 3,5,7,9, and 11, just enter:
>>x=[3 5 7 9 11] <enter> % define a row vector
MATLAB should return
x =
3 5 7 9 11
Column Vector
Column vectors have similar constructs to row vectors, but semicolons separate the
entries.
>>x=[3; 5; 7; 9; 11] <enter> % define a column vector
Row Vector Column Vector
It is possible to turn a row vector into a column vector (and vice versa) via a process
called transposing and defined using the prime operator (apostrophe), [].
>>x=[3 5 7 9 11]; <enter> % specify a row vector
>>x <enter> % convert a row vector into a column vector
Evenly Spaced Vectors
This way of defining vectors becomes awkward for large data sets (this can be time
consuming), moreover, common vectors are those of equally spaced numbers.
MATLAB provides a more flexible way of constructing vectors of evenly spaced
values over a given range. The colon operator [:] is used for this purpose. The colon
will be used most often to generate vectors for creating x-y plots. The general form of
18
the statement is:
>>x=start:step:end;
where start and end are the lower and upper bounds of the interval and step
(increment) is the step size.
Practice
-Evenly Spaced Vector-
(1)
x=0:0.1:1 <enter> % generate 11 data pts from 0 through 1 in increments of 0.1
x = Columns 1 through 9
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000
0.8000
Columns 10 through 11
0.9000 1.0000
You can reference individual items within the vector. To change the sixth element
in the x vector, proceed as follows:
>>x(6)=0.45
NOTE
It is just as easy to use negative increments.
>>x=7:-1;2 <enter> % generate an array with negative step size
If the step size is omitted, a value of 1 is used.
>>x=0:5 <enter> % generate an array with step size of 1
19
Practice
- Even Increment-
(2)
Compute the sum of the finite geometric series
2
1 ...
n
s r r r = + + + +
Where the common ratio is r=0.6 and n=10.
>>n=0:10;
>>r=0.6;
>>s=sum(r.*n) <enter>
%define the running index n
% specify the ratio of the geometric series
% evaluate the partial sum
Practice
-Even Increment-
(3)
We are given a vector x=[0:0.2:3].
1. Determine the seventh component of x
2. Determine the length of x
>>x=[0:0.2:3]; % specify vector x
>>x(7) % specify the seventh component of x
>>length (x) <enter> % return the length of the vector x
NOTE
In MATLAB, all arrays are indexed starting with 1, i.e., x(1) is the first element of the
array x. The notation x(1:12) means the first 12 elements of the vector x.
Length vs. size: The length of a vector is the number of values it holds. The size of a
vector is the number of rows by the number of columns.
20
Product of Vectors
Practice
-Product of Vectors-
Compute the dot product of the following vectors:
>>x=[1 2 3];
>>y=[4 5 6];
>>x*y <enter>
Commands for Generating Vectors
- linspace & logspace
A. linspace Command
MATLAB has two built-in functions to generate vectors. The linspace function
creates linearly spaced vectors of length n over the range from start to end (if the
length is omitted, MATLAB assumes 100 points). The command structure is as
follows:
>>x=linspace (start,end,n);
Practice
-linspace Command-
Write a piece of code to convert temperatures from degrees Fahrenheit to degrees
centigrade.
>>F=linspace(0,9,10); <enter> % specify evenly spaced temperatures
>>C=(F-32)*5/9; <enter> % Fahrenheit to Centigrade conversion
>>[F C] <enter> % display both temperatures as column vectors
ans =
0 -17.7778
1.0000 -17.2222
2.0000 -16.6667
3.0000 -16.1111
4.0000 -15.5556
5.0000 -15.0000
6.0000 -14.4444
7.0000 -13.8889
8.0000 -13.3333
9.0000 -12.7778
21
B. logspace Command
The function logspace generates a logarithmically spaced vector of length n ranging
from 10
start
to 10
end
. The command structure is as follows:
>>x=logspace(start,end,n)
>>x=logspace(0,2,5) <enter> % create a vector of length 5 ranging from 1 to 100
Term-by-term Operations
MATLAB has special operators, to carry out term-by-term multiplication, division,
and exponentiation. An operator preceded by a dot (or period) causes the operation to
be performed term-by-term. These operators are shown in the following table:
SYMBOL TERM-BY-TERM OPERATION
.* Multiplication
./ Division
.^ Exponentiation
Suppose that we have the vectors
| |
1 2
, ,...,
n
x x x x = and
| |
1 2
, ,...,
n
y y y y = . Then
x.*y=| |
1 1 2 2
, ,...,
n n
x y x y x y
x./y=
1 2
1 2
, ,...,
n
n
x x x
y y y
(
(
x.^p=
1 2
, ,...,
p p p
n
x x x (
22
Practice
- Term-by-term Operations-
(1)
>>% Term-by-term multiplication
>>x=[1 2 3]; % specify vector x
>>y=[2 4 1]; % specify vector y
>>z=x.*y <enter> % compute the term by term product
>>%Term-by-term division
>>x=[1 2 3] % specify vector x
>>y=[2 4 1]; % specify vector y
>>z=x./y <enter> % compute the term by term division
>>%Term-by-term exponentiation
>>x=[1 2 3]; % specify vector x
>>y=[2 4 1]; % specify vector y
>>z=x.^y <enter> % compute the term by term
exponentiation
Practice
- Term-by-term Operations -
(2)
A supermarket conveyor belt holds an array of groceries.
Product Quantity Unit Price Sub_total
A 4 1.5 4 x 1.5
B 3 0.5 3 x 0.5
C 2 2.5 2 x 2.5
D 5 0.95 5 x 0.95
Total 17.25
The prices of each product (in pounds) are [1.5 0.5 2.5 0.95]; while quantities of
each product are [4 3 2 5]. Use MATLAB to calculate the total bill.
>> price=[1.5 0.5 2.5 0.95];
>> quantity=[4 3 2 5];
>> sub_total= price.*quantity
>> total= sum(sub_total)
23
- Complex Arithmetic & Algebra
MATLAB can handle both real as well as complex data. In this section, we shall
explore the use of MATLAB for doing complex arithmetic and algebra.
Usage of Variable i or j
The number, 1 , is identified in MATLAB by the variables i or j. Using j (i is
typically dedicated to electrical current), one can generate complex numbers.
Therefore, a complex number, such as z=3+5j, may be input as z=3+7j or z=3+7*j.
MATLAB always displays the imaginary unit as i.
Practice
- Usage of variable i or j-
>>z=2+3j; % define a complex number z
Commands for Complex Numbers
A. real(z) & imag(z)
MATLAB provides several built-in functions to work with complex numbers. We can
extract the real and imaginary parts of an arbitrary complex number by the functions
real(z) and imag(z).
Practice
-Commands: real(z) & imag(z)-
>>z=3+5j; <enter> % define a complex number z
>>x=real(z) <enter> % extract the real part of z and store the result in x
>>y=imag(z) <enter> % extract the imaginary part of z and store the result in y
B. abs(z), angle(z) & conj(z)
To convert to polar notation, the function abs(z) and angle(z) ( ) ( )
angle z < ,
24
compute the modulus (magnitude) of the complex number and its phase in radians,
respectively. Lastly, conj(z) returns the complex conjugate of the complex number z.
Practice
-Commands: abs(z), angle(z) & conj(z)-
>>z=5+3j; % define a complex number z
>>mag=abs(z) <enter> % compute the magnitude of z
>>phase=angle(z) <enter> % compute the phase in radians
>>phase=angle(z)*180/pi <enter> % compute the phase in degrees
>>zbar=conj(z) <enter> % compute the complex conjugate of z
Summary of basic functions for manipulating complex numbers, where z is a complex
number:
Matlab Command Meaning
real(z)
imag(z)
abs(z)
angle(z)
conj(z)
Re(z)
Im(z)
|z|
z
z*
C. cart2pol & pol2cart Command
It is often the case to convert a complex number from a Cartesian form to polar form
and vice versa. MATLAB has built-in functions cart2pol and pol2cart that perform
conversion from Cartesian to polar and polar to Cartesian, respectively.
Function Synopsis
>>z1=x+j*y; % define a complex number in Cartesian form
>>z2=mag*exp(j*theta); % define a complex number in polar form
>>[theta, mag]=cart2pol(x,y); % conversion from Cartesian to polar
>>[x,y]=pol2cart(theta, mag); % conversion from polar to Cartesian
25
Practice
-cart2pol Command-
Express the given complex number in polar form
>> z=-2+0.5j; % define a complex number in Cartesian form
>>[theta, mag]=cart2pol(-2,0.5) % provide polar form of z
theta =
2.8966
mag =
2.0616
2.8966
2 0.5 2.061
j
z j e = + =
Practice
-Complex Numbers-
(1)
1. Use MATLAB to evaluate the magnitude and phase of the given complex
numbers.
>>z1=2+3j;
>>z2=2+j;
>>z3=-2-3j;
>>z4=1-3j;
2. Express the numbers defined in part (1) in polar form
3. Determine z1*z2, and z1/z2
4. Determine z3+z4, and z4-z3
5. Determine the real part of
2 2
( 1) ( 2) z z
6. Determine the imaginary part of
4 3
( 1) /( 2) z z
Plot z1 using plot(z1,x). This command will plot the imaginary part versus the
real part.
26
Practice
-Complex Numbers-
(2)
Check the following identities:
1.
2
j
e j
=
2.
2
j
e j
=
3. 1
j
e
=
>> exp(j*pi/2)
>>exp(-j*pi/2)
>>exp(j*pi)
Practice
- Complex Numbers-
(3)
Simplify the following expressions:
1. ( )
5
1 z j =
>>z=(1-j)^5
2.
3
j
z je
=
>>z=j*exp(j*pi/3)
3.
(2 3 )(4 9 )
(1 5 )(7 6 )
j j
z
j j
+
=
+
>>z=((2+3j)*(4-9j)/((1+5j)*(7-6j))
5. ( )
3
1
j
z j e
= +
>> z=(1+j)*exp(-j*pi/3) <enter>
4.
3 2
j j
z e e
= +
>>z=exp(j*pi/2)+exp(-j*pi/3);
27
Practice
-Complex Numbers-
(4)
Simplify the following complex-valued expressions and give the answers in both
Cartesian form and polar form.
1.
2 3
3 4
3 5
j j
e e
+
2.
( )
4
7 5 j +
3.
( )
2
5 7 j
4.
2
7 7
Im
j j
je e
| |
+
|
\
5.
2
5 3
Re
j j
je e
| |
|
\
Practice
-Complex Numbers-
(5)
The following circuit is driven by a source delivering a voltage of 2v with a
frequency of 1kHz.
1. Determine the impedance of the circuit
2. Find the current through the circuit
3. Find the voltage across the resistor
4. Find the voltage across the capacitor
Solution
>>% Specify the values of components
>>V=2; R=le+3; C=le-6; omega=2*pile+3;
>>Z_C=-j/(C*omega);
>>Z=R+Z_C; % impedance of the circuit
>>I=V/Z; % current through the circuit
>>V_R=I*R; % voltage across the resistor
>>V_C=I*Z_C; % voltage across the capacitor
28
Polynomials are quite common in electrical engineering. Transfer functions
characterizing linear systems are typically ratios of two polynomials (rational
functions). MATLAB represents polynomials as row vectors containing the
coefficients of the powers in descending order. For instance, the polynomial
( )
2
2 4 5 P s s s = + + can be expressed as a vector by entering the statement P=[2 4 5],
where the variable P is the name we have assigned to the polynomial. MATLAB can
interpret a vector of length (n+1) as an n-th order polynomial. Missing coefficients
must be entered as zero. MATLAB provides functions for standard polynomial
operations, such as polynomial roots, evaluation, and differentiation.
Basic Polynomial Commands
A. The roots Command
The roots function extracts the roots of polynomials. If p is a row vector containing
the coefficients of a polynomial, roots(p) returns a column vector whose elements are
the roots of the polynomial.
Practice
-The roots Command-
Find the roots of the polynomial ( )
3 2
2 3 4 p s s s s = + + + [1 2 3 4]
>>p=[1 2 3 4]; % specify polynomial p(s)
>>roots(p) <enter> % provide the roots of the polynomial p(s)
ans =
-1.6506
-0.1747 + 1.5469i
-0.1747 - 1.5469i
29
B. The poly & polyval Commands
The poly command is used to recover a polynomial from its roots. If r is a vector
containing the roots of a polynomial, poly(r) return a row vector whose elements are
the coefficients of the polynomial.
The polyval command evaluates a polynomial at a specified value. If p is a row
vector containing the coefficients of a polynomial, polyval(p,s) return the value of the
polynomial at the specified value s.
Practice
-The poly & polyval Commands-
The roots of a polynomial are -1, -2, -3 j4. Determine the polynomial equation
>>r=[-1 -2 -3+4*j -3-4*j]; % define the roots of a polynomial
>>p=poly(r) <enter> % extract the polynomial p from its roots
p =
1 9 45 87 50 ( )
4 3 2
9 45 87 50 p s s s s s = + + + +
>>% Evaluation of polynomials
>>p=[1 2 3 4]; % define a polynomial p(s)
>>val=polyval(p,1) <enter> % evaluate the polynomial p(s) at s=1
30
Practice
-roots & polyval Command-
A linear time-invariant (LTI) system is specified by its transfer function given by
3 2
4 3 2
3 2 5
( )
2 5 3 1
s s s
H s
s s s s
+ + +
=
+ + + +
1.Use MATLAB to evaluate its poles and zeros
2.Evaluate H(s) at s=2j
3.Find the magnitude of H(2j)
4.Find the phase of H(2j)
Solution
>>num=[1 3 2 5]; % specify numerator of H(s)
>>zero=roots(num); % determine the zeros of H(s)
>>den=[1 2 5 3 1]; % specify denominator of H(s)
>> pole=roots(den); % provide the poles of H(s)
>>H=polyval(num, 2j)/polyval(den,2j); %evaluate H(s) at s=2j
>> mag=abs(H); % specify the magnitude
>>phase=angle(H)*180/pi; % specify the phase in degrees
B. The tf2zp Command
The zeros, poles, and gain of a transfer function can also be found via tf2zp command,
as illustrated below.
Practice
-The tf2zp Command-
>>num=[1 3 2 5]; % specify numerator of H(s)
>>den=[1 2 5 3 1]; % specify the denominator of H(s)
>>[z,p,k]=tf2zp(num,den); % extract zero, poles and gain of H(s)
NOTE
z=zeros
p=poles
k=gain
31
D. The zp2tf Command
To find the numerator and denominator polynomials of a transfer function H(s) from
the zeros(z), poles(p), and gain(k), we use the command zp2tf.
Practice
- The zp2tf Command-
(1)
>>z=[1+2j; 1-2j]; % zeros as a column vector
>>p=[-3; -2+5j; -2-5j]; % poles as column vector
>>k=1; % gain set equal to unity
>>[num,den]=zp2tf(z,p,k); % provide the transfer function
Practice
- The zp2tf Command-
(2)
A system has zeros at -6, -5, 0 and poles at 3 4 j , -2, -1, and a gain of unity.
Determine the system transfer function.
>>z=[-6; -5; 0]; % specify zeros
>>k=1; % specify the gain
>>p=[-3+4*j; -3-4*j; -2; 1]; %specify poles
>>[num,den]=zp2tf(z,p,k) <enter> % numerator &denominator of transfer function
num =
0 1 11 30 0
den =
1 7 29 13 -50
>>sys=tf(num,den) <enter> % print the transfer function of the system
Transfer function:
S^3+11 s^2+30s
-----------------------
S^4+9s^3+45s^2+87s+50
32
E. polyder Command
Differentiation of polynomials is a straightforward procedure, one that MATLAB
implements with the function polyder.
Function Synopsis
>>s=polyder(p); % return the derivative of polynomial
>>s=polyder(p,q); % give the derivative of the product p(x).q(x)
Polynomial multiplication
-The Usage of the conv Command
The product of two polynomial p(x) and q(x) is found by taking the convolution of
their coefficients. MATLAB makes use of the conv function to obtain the coefficients
of the required polynomial product. The coefficients should be in the order of
decreasing power. Multiplication of more than two polynomials requires repeated use
of conv.
Practice
- The conv Command-
(1)
Consider the following two polynomials,
( )
2
2 3 2 p x x x = + +
3 2
( ) 4 5 7 1 q x x x x = + + +
Find the coefficients of the product polynomial ( ) ( ) ( ) y x p x q x =
>>p=[2 3 2 ]; % define p(x) in vector form
>>q=[4 5 7 1]; % define q(x) in vector form
>>y=conv (p,q) % compute the product polynomial in vector form
y =
8 22 37 33 17 2
The screen output displays the coefficients of the resultant product polynomial in
descending order. This means that the product polynomial is given by
( )
5 4 3 2
8 22 37 33 17 2 y x x x x x x = + + + + +
33
Practice
- The conv Command-
(2)
Find the product of the following three polynomials
( )
( )
( )
5
2 3
7 8
p x x
q x x
r x x
= +
= +
= +
>>p=[1 5];
>>q=[2 3];
>>r=[7 8];
>>product=conv(r,conv(p,q)) <enter>
product =
14 107 209 120
3 2
14 107 209 120 product x x x = + + +
Polynomial Division
- The Usage of the deconv Command
Division of polynomials is achieved by the deconvolution function deconv. The
deconv function will return the remainder as well as the result.
Function Synopsis
>>[Q,R]=deconv(num,den);
This function returns two polynomials Q(s) (Quotient), and R(s) (remainder) such that
num(s)=Q(s) den(s)+R(s).
34
Practice
-The deconv Command-
Consider the following improper rational function,
( )
( )
( )
3
2
3 5
4 3
B x x x
D x
A x x x
+
= =
+
which can be written as,
( ) ( )
( )
( )
R x
D x Q x
A x
= +
where Q(x) is returned as zero if the order of B(x) is less than the order of A(x)
>>B=[1 0 3 -5]; % specify the polynomial B(x) in vector form
>>A=[1 4 -3]; % specify the polynomial A(x) in vector form
>>[Q,R]=deconv(B,A) % perform division
Q =
1 -4
R =
0 0 22 -17
( ) ( )
3
2 2
3 5 22 17
4
4 3 4 3
x x x
D x x
x x x x
+
= = +
+ +
Basic Functions
The graph of function provides a tremendous insight into the functions behavior and
can be of great help in the solution of a problem. MATLAB is capable of generating a
wide range of graphics, from simple plot to 3-D plots. We shall focus on the most
fundamental and most widely used of the MATLAB plotting capabilities. The basic
functions are plot, semilogx, semilogy, loglog, polar and stem. These commands
have similar basic form. The plot(x,y) command generates a plot of the values in the
vector y versus the values in the vector x on a linear scales. The x values will appear
on the horizontal axis and the y values on the vertical axis. The semilogx(semilogy),
35
indicates that the x-axis (y-axis) is logarithmic, and the other axis is linear. In the
loglog function both axes are logarithmic. The polar uses polar coordinates and stem
works just like the plot command except that the plot created will have a vertical line
at each value rather than a smooth curve, a type of plot that is very often used in signal
processing for visualizing sequences. Sometimes it is necessary to plot two functions
on the same graph even when the abscissa range and function values differ. This can
be accomplished via the MATLAB command plotyy. The plotyy command puts the
first function value range on the left-hand vertical axis, and the range of values for the
second function on the right-hand vertical axis.
Syntax
>>plotyy(t1,y1,t2,y2)
Plots y1 versus t1 with y-axis labeling on the left and y2 versus t2 with y-axis labeling
on the right.
>>plotyy(t1,y1,t2,y2,function)
Uses the plotting function specified by the string function instead of plot to produce
each graph. The string function can be plot, semilogx, semilogy, loglog, or stem.
All plots generated by the plotting commands appear in a figure window.
Practice
- The plotyy Command-
>>t=0:pi/100:2*pi;
>>y1=sin(t)
>>y2=0.5*sin(t-1.5);
>>plotyy(t,y1,t,y2,stem)
MATLABs Polar Command
Some plots are better drawn in polar coordinates. Instead of the (x,y) Cartesian
coordinates, we use an angle theta and radius r to locate a point in the plane. The
MATLAB routine polar enables users to easily draw the graphs of polar equations
having the form r=f( )
36
Practice
-MATLABs Ploar Command-
Sketch the graph of r=sin(2 )
>>theta=linspace(0,2*pi,100);
>>r=sin(2*theta);
>>polar(theta,r);
Polar to Cartesian Transformations
The polar to cartesian transformations
X=rcos( )
Y=rsin( )
enable the user to employ MATLABs plot command
Practice
-Polar to Cartesian Transformations-
(1)
>>theta=linspace(0,2*pi,100);
>>r=sin(2*theta);
>>x=r.*cos(theta);
>>y=r.*sin(theta);
>>plot(x,y);grid
37
Practice
-Polar to Cartesian Transformations-
(2)
The plot command, which directly plots vectors of magnitude and angle, is polar.
The equation of cordioid in polar form, with parameter a is given by
( ) ( )
1 cos r a = + , 0 2
>>a=1;
>>theta=0:2*pi/200:2*pi;
>>r=1+cos(theta);
>>polar(theta,r)
Line, Marks and Colors
- Basic Functions
When plotting multiple curves, it is desirable to vary the colors, plot symbols and line
styles (dashed, dotted, etc.) associated with each line. This feature is accomplished
by adding another argument to the plot command.
NOTE
Line styles and marks allow you to discriminate different data sets on the same plot
when color is not available.
Syntax
>>plot (x,y, linestyle_mark_color);
with no separators between the options. The options can be in any order.
38
Practice
-Lines, Marks & Colors-
>>plot(t,y,:); % plot y versus t using a dotted line
>>plot(t,y,r:); % plot y versus t using a dotted line in red
>>plot(t,y,-.ro); % plot y versus t using a dash-dot line (-.),
colored red (r) and (o) at the data points
>>% and place places circular maker
Symbol of Lines, Marks & Colors
The line styles and colors consist of character string whose first character specifies the
color (optional) and second the line style, enclosed in single quotes. The options for
line styles, marks, and color are depicted below.
Symbols of Line:
LINE SYMBOL
Dash --
Dashdot -.
Dotted :
Solid -(default)
Symbols of Color:
COLOR SYMBOL
Blue b
Black k
Cyan c
Green g
Magenta m
Red r
Write w
Yellow y
Symbols of Mark:
MARK SYMBOL
Circle O
Point .
Plus +
Star *
X-mark x
Square s
Diamond d
Pentagrom p
Hexagram h
39
Practice
- Symbols of Lines & Color-
(1)
>>t=0:0.01:2 % define a time vector
>>y=cos(2*pi*4*t) % define a vector y
>>plot(t,y,*r) % plot y versus t by (*) marks in red color
Practice
- Symbols of Lines & Color-
(2)
>>%Taylor series approximation of exp(x) near x=1
>>x=0:0.01:3;
>>p1=exp(x);
>>p2=exp(1)+exp(1)*(x-1);
>>p3=exp(1)+exp(1)*(x-1)+exp(1)*(x-1).^2/2;
>>p4=exp(1)+exp(1)*(x-1)+exp(1)*(x-1).^2/2+exp(1)*(x-1).^3/6;
>>plot(x,p1,'m-',x,p2,'g--',x,p3,'r-',x,p4,'k:','LineWidth',3)
>>legend('exp(x)','n=1','n=3','n=3')
>>title('Taylor series approximation of exp(x) near x=1', 'Fontsize',12)
>>xlabel('x','Fontsize',13)
>>ylabel('e^{x}','FontSize',13)
>>grid
40
Graphics Handles
When using the plotting command, MATLAB draws the graph using a number of
graphics objects, such as line, text, and surfaces. All graphics objects have a set of
properties that control the appearance and behavior of the object. For example a line
is an object with properties such as line style, color, and thickness. It is possible,
under MATLAB, to access and modify these properties.
A. The Main Functions
MATLAB assigns a unique identifier to every object in the figure window. This
number is called the handle of the object. The handle of the figure is an integer, and
all other handles are floating-point numbers. You can use this handle to access the
objects properties. The commands xlabel, ylabel, title and text return handles to the
objects they create.
>>h1=plot(x,y,mo); % make a plot and return graphics object handle
>>h2=xlabel(time,[s]); % label the horizontal axis and return handle
>>h3=ylabel % label the vertical axis and return handle
The variable h1, for example, holds information about the graph you generated and is
called the handle graphics. You may view the list of properties and their values with
command get(handle).
Practice
-Graphics Handles: The Main Functions-
>>t=0:0.01:2; % define the time vector
>>y=sin(2*pi*3*t); % specify the corresponding y-vector
>>h1=plot(t,y); % generate a plot and return handle
>>h2=xlabel(time,[s]; % label the time axis and return handle
>>h3=ylabel(Amplitude,[v]); % label the voltage axis and return handle
>>h4=title(Sine wave); % add title and return handle
>>get(h2) % list all properties of h2 and their values
(Continue on next page)
41
Color = [0 0 0]
EraseMode = normal
Editing =off
Extent = [0.87468-1.35849 0.234294 0.169811]
FontAngle = normal
FontName = Helvetica
Fontsize = [10]
FontUnits = points
FontWeight =normal
HorizontalAlignment = center
Position = [0.997436-1.22275 17.3205]
Rotation = [0]
String =time,[s]
Units=data
Interpreter = tex
VerticalAlignment = cap
BeingDeleted = off
ButtonDownFcn =
Children = []
Clipping = off
CreateFcn =
DeleteFcn =
BusyACtion = queue
HandleVisibility = off
HitTest = on
Interruptible = on
Parent = [100.001]
Selected = off
SelectionHighlight = on
Tag =
Type = text
UIContextMenu =[]
UserData=[]
Visible = on
42
B. Additional Functions
- gcf, gca & gco
There are several functions that are useful for accessing handles of current objects.
These are:
gcf(get current figure) % return the handle of current figure
gca(get current axis) % return the handle of current axes
gco(get current object) % return the handle of current object
Syntax
>>h2=get(gca,xlabel)
>>h3=get(gca,ylabel)
>>h4=get(gca,title)
% provide handle of xlabel
% provide handle of ylabel
% provide handle of title
The following commands provide the list of properties:
>>get(gcf)
>>get(gca)
>>get(gco)
% list all properties of the figure
% list all properties of the axes
% list all properties of an object
C. The set Command
The set function allows the setting of objects property by specifying the objects
handle and any number of property name/property value pairs.
Syntax
>>set(handle,property_name, property_value)
For instance, to change the color and width of the line, proceed as follows:
>>set(handle, color, [0 0.8 0.8], LineWidth, 3)
To obtain a list of all settable properties for a particular object, call set with the objects
handle.
>>set(handle)
43
Practice
- Graphics Handles: Additional Functions & The set Command-
>>t=0:0.01:2; % define time vector
>>x=3+2*cos(2*pi*3*t); % define the dependent vector x
>>h1=plot(t,x); % plot and get handle
>>set(hi,LineWidth,3); % set thickness to 3
>>h2=xlabel(time,[s]); % label axis and get handle
>>set(h2,FontSize,13); % set the font size of x-label to 13
>>set(gca,Xtick,0:0.25:2); % set X-tick
>>h3=ylabel(Amplitude,[v]); % label axis and get handle
>>set(gca,Ytick,0:0.5:5); % set Y-tick
>>set(h3,FontSize,13); % set font size of y-label to 13
>>h4=title(Sinusoidal waveform); % add title and get handle
>>set(h4,color,[0.6 0.3 0.4],FontSize,13); %set color and font size of title
D. Additional Information
It is also possible to change the attributes of the line width and the marker colors with
commands like:
LineWidth
MarkerEdgeColor
MarkerFaceColor
MakerSize
Width (in points) of the line
Color of the marker or the edge color four filled markers
Color of the face of filled markers
Size of the maker in points
Once a waveform is plotted, one can change the style and feel by providing additional
information.
44
Practice
- Graphics Handles: Additional Information-
>> x=linspace(0,2*pi,60);
>> y=sin(2*x);
>> plot(x,y,'-mo','LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor',[.48 1 .62],...
'MarkerSize',10)
This script produces a plot of sin(3x) using a solid magenta line of width 2 point
drawn with circular markers of size 10 point at the grid nodes which are colored
mint green internally and have a black edge.
Commands
A. figure(n) Command
When the plot command is executed, a graphics window appears automatically. It is
possible to open as many figure windows as memory permits. To create a new
window use the command figure(n). MATLAB numbers figure windows starting at 1.
>>figure(2); % pop up a new graphics window
B. clf & close(n) Commands
A Figure can be cleared using the clf command, and closed by entering close(n) when
n is the number of the window to close.
45
Overlaying Plots
It is often desirable to overlay two plots on the same set of axes. To overlay plots, you
tell MATLAB to hold the previous plot using hold on and subsequent graphs will be
on the same axes. The hold command will remain active until it is turned off, by
entering hold off.
Practice
-Overlaying Plots-
(1)
>>t=0:0.01:2; % define a time vector
>>y=cos(2*pi*4*t); % define vector y
>>plot(t,y); % plot y versus t
>>z=sin(2*pi*3*t); % define vector z
>>hold on % hold the previous plot
>>plot(t,z) % overlay plots
>>hold off % turn off the hold function
Similarly, several signals with equal number of data points may be displayed in the
same frame against the same axis as follows:
Practice
-Overlaying Plots-
(2)
>>t=0:0.01:2 % define a time vector
>>x1=sin(2*pi*3*t); % define vector x1
>>x2=cos(2*pi*2*t); % define vector x2
>>x3=abs(x2); % define vector x3
>>x=[x1;x2;x3]; % matrix of data
>>plot(t,x); % plot 3 signals against time
If, on the other hand, the curves are plotted against different vectors, we use,
>>plot(t2,x2,t2,x2,t3,x3)
46
This command plots x1 versus t1, x2 versus t2, and x3 versus t3. In this case, t1,t2,
and t3 may be of different sizes, provided that x1, x2, and x3 are of the same size as
their corresponding time vector t1, t2, and t3, respectively.
Practice
-Overlaying Plots-
(3)
>>plot(t1,x1,r,t2,x2,g) % plot x1 in red and x2 in green
Plotting Practices
Practice
- Plotting Practice-
(1)
Plot the discrete-time signal specified by x[n] =cos 2
13
n
| |
|
\
>>n=0:1:24; % define a vector n
>>x=cos(2*pi*n/13); % define vector x
>>stem(n,x) % plot x versus n
Practice
-Plotting Practice-
(2)
We shall try now semilog plots.
>>t=linspace(0,2*pi,200);
>>x=exp(-2*t)
>>y=t;
>>semilog(x,y);grid
% generate 200 linearly spaced points in [0.2]
% define the function x(t)
% define the function y(t)
% provide a semilog plot of y versus x
The command grid will place grid lines on the current graph.
47
Practice
-Plotting Practice-
(3)
The voltage across a capacitor during discharge was recorded as a function of time.
Time (s) 6 10 17 25 32
Voltage (volts) 98 62 23 9.5 3.5
>>time=[6 10 17 25 32]; % time vector
>>voltage=[98 62 23 9.5 3.5]; % capacitor voltage
>>semilogy(time,voltage);grid % plot voltage versus time
>>title(Voltage of discharging capacitor)
>>xlabel(Time (sec))
>>ylabel(Voltage (volts))
NOTE
It is very important to always label your axes with units. This is engineering, not
mathematics we deal with physical quantities.
3-D Plotting
It is often desirable to plot functions of the form z=f(x,y). As with two dimensional
plots, we first define a two-dimensional grid in the xy plane, then evaluate the function
at the grid points to determine points on the three dimensional surface.
48
A two-dimensional grid in the xy plane is defined in MATLAB by two vectors, one
containing the x-coordinates at all points in the grid, and the other containing the
y-coordinates. When you want x and y to vary over some range, you need a matrix
(rather than a vector) for x and y to get a complete domain that covers all the different
combinations of those x and y values over some range. The meshgrid function
creates 2 matrices X and Y from the x and y vectors. The rows of the resulting matrix
X are formed by repeating the vector x and the columns of the matrix Y are formed by
repeating the vector y.
Practice
-3-D Plotting-
(1)
x=-2:2;
y=-3:3;
[X,Y]=meshgrid(x,y)
(X,Y)=(-2,0)
49
Practice
-3-D Plotting-
(2)
>>x=0:0.01:10;
>>y=x;
>>[X,Y]=meshgrid(x,y);
>>Z=3*sin(sqrt(X.^2+Y.^2));
>>mesh(X,Y,Z)
Practice
-3-D Plotting-
(3)
>>x=-2:0.1:2;
>>y=-3:0.1:3;
>>[X,Y]=meshgrid(x,y);
>>Z=exp(-(X.^2+Y.^2));
>>surf(X,Y,Z)
50
Changing the Viewing Direction
Viewing the surface from different angles: The viewing angle is specified by the view
command view(az,el) where az is the azimuth in degrees, measured positive
counterclockwise, and el is the elevation in degrees above the xy plane. The default
view is (-37.5, 30).
3-D Plotting Table
The following Table summarizes the most popular 3D plotting functions.
3D Plotting Functions
Matlab Command Meaning
plot3 Simple x-y-z plot
contour Contour plot
contourf Filled contour plot
contour3 3D contour plot
mesh Wireframe surface
meshc Wireframe surface plus contours
meshz Wireframe surface plus curtain
surf Solid surface
surfc Solid surface plus contour
waterfall Unidirectional wireframe
bar3 3D Bar graph
bar3h 3D Horizontal bar graph
pie3 3D Pie chart
fill3 Polygon fill
comet3 3D Animated, comet-like plot
scatter3 3D Scatter plot
stem3 Stem plot
51
Contour Plots
Both 2D and 3D contour plots can be produced. contour(z) produces a 2D plot of the
matrix z, when the z values are treated as heights above the 2D plane. It is also
possible to override the default number of contour lines (20) by choosing the number
of lines required; for example, for integer N,
Practice
-Contour Plots-
>>z=peaks(24);
>>figure;
>>subplot(1,2,1); contour(z);
>>subplot(1,2,2; contour (z,10);
Bar Graph
A bar graph is a diagram that compares bars of the same width but of different heights
according to the data they represent. A bar graph may be horizontal or vertical. Bar
graphs are one of the many techniques used to present data in a visual form in order to
recognize patterns or trends.
Practice
-Bar Graph-
(1)
>> x=-3:0.2:3;
>>y1=sin(x); y2=sin(x)/2;
>>subplot(2,2,1);bar(x,y1);title('2-D Bar graph--vertical')
>>subplot(2,2,2);bar3(x,y1);title('3-D Bar graph')
>>subplot(2,2,3);barh(x,y1);title('2-D Bar graph--horizontal')
>>subplot(2,2,4);bar(x',[y1' y2'],'stacked');title('2-D Bar graph--stacked')
52
Practice
-Bar Graph-
(2)
>>x=[1 2 3 4];
>>b1=[3 5 7 9];
>>b2=[1.5 2.7 3.2 6.7];
>>b=[b1;b2];
>>bar(x,b,grouped); colormap(cool)
Pie Charts
A pie chart is a circle graph divided into pieces, each displaying the size of some
related piece of information. A pie chart is produced with the command pie(x); it is
also possible to explode one or more segments of the pie for emphasis.
Practice
-Pie Charts-
(1)
Enrollment data in the school of engineering at a local university is summarized in
the following table:
Engineering Discipline No. of Students Fraction of Total
Civil
Electrical
Industrial
Mechanical
Chemical
Total
480
908
240
620
140
2388
0.20
0.38
0.10
0.26
0.06
1.00
Draw a pie chart of the distribution of students in the school of engineering.
>>x=[480 908 240 620 140];
>>y={civil,Electrical,Industrial,Mechanical,Chemical}
>>pie(x,y)
53
Practice
-Pie Charts-
(2)
>>x=[1.3 2.5 4.4 6.7];
>> subplot(2,2,1);pie(x);
>>subplot(2,2,2); pie(x,[0 0 0 1])
>>subplot(2,2,3);pie(x,{'GM','IBM', 'DELL','HP'});
>>subplot(2,2,4);pie3(x,[0 1 0 0])
Subplots
MATLAB graphics window accommodates a single plot by default, but it is possible to
create an array of subplots within the one figure. The subplot command allows a
given figure window to be broken into a rectangular array of plots, each addressed with
the standard plot commands.
>>subplot(r,c,w)
The arguments r and c are the number of rows and columns into which the graphics
window is divided, respectively. The w designates the position of the graph.
Windows are numbered from left to right and top to bottom within the figure. For
example, subplot(2,1,1) partition the graphics window into two rows in a single
column and fits the plot on the top cell. Figure 1 depicts two possible subplots
arrangement.
54
2
r
o
w
s
2
r
o
w
s
Customizing Plots
A. Basic Functions
-Commands: title, xlabel, ylabel, grid & legend
MATLAB provides means to improve the appearance and clarity of the plots. Once a
plot is on the screen, it may be given a title, axes labeled and text placed within the
graph. The title command is used to place a title above the plot, xlabel writes text
beneath the x-axis, and ylabel writes a text besides the y-axis of a plot. They each
take a string variable, which must be in single quote. The grid command toggles a
grid on and off in the current figure, the legend commend adds a legend to an existing
graph (movable with the mouse) that automatically uses the right symbols and colors
and sticks the description in the legend command after them, and the text command
allows a string of text to be placed at a particular x-y position on the graph.
Syntax
>>xlabel(label); % write label beneath the x-axis
>>ylabel(label) % write label besides the y-axis
>>title(label); % place a title above the plot
>>text(x,y,label); % write label at the location(x,y)
>>grid % draw a grid on the graph area
>>legend(first plot, second plot); % place a legend within a graphics window
Note
It is very important to always label your axes with units. This is engineering, not
mathematics we deal with physical quantities.
55
Practice
-Customizing Your Plots-
(1)
>>t=-2*pi:0.02:2*pi; % define a time vector
>>y=sin(t).*cos(t).^2; % define a dependent vector y
>>plot(t,y);grid; % plot y versus t
>>xlabel(time,[s]) % annotate the t-axis
>>ylabel(amplitude,[v]; % annotate the y-axis
>>legend(trig function) % add a legend to plot
B. Interactive Labeling & Coordinates of Points
-Commands: gtext & griput
The gtext command provides interactive labeling. After generating the plot, enter the
following command:
>>getext(label)
This command places text on the graph by showing a crosshair on the graphics window.
After the crosshair is positioned where you want the text to appear, press the mouse
button. The griput command determines the coordinates of points on the graph.
>>[x,y]=ginput(n); %provide coordinates of n points on a graph
Position the mouse cursor on a point of a graph for which you want to know the
coordinates, and click the mouse button, then repeat the process for the remaining (n-1)
points. When done, hit the carriage return (enter key), and the n-coordinates will be
shown on the command window.
C. Redefine Your Axis
-Commands: axis, axis(square), axis off & axis on
MATLAB automatically selects the appropriate ranges and tick marks for the graph,
but it is often necessary to redefine it. The axis command manually sets the axis
limits. This command is implemented as follows:
>>axis([xmin xmax ymin ymax])
56
where xmin xmax ymin ymax are the desired maximum and minimum values for the
x and y axes, respectively.
The command axis(square) ensures that the same scale is used on both axes. You
can remove the axes from your graph and put them back via axis off and axis on,
respectively.
The following Table shows a list of Matlab commands used to control the axes.
Some Matlab Commands for Controlling the Axes
Mathematical notation: Meaning:
axis([xmin xmax ymin ymax]) Set specified x- and y-axis limits
axis auto Return to default axis limits
axis equal Equalize data units on x-, y- and z-axes
axis off Remove axes
axis on Put axes back
axis square Make axis box square (cubic)
axis tight Set axis limits to range of data
xlim([xmin xmax]) Set specified x-axis limits
ylim([ymin ymax]) Set specified y-axis limits
Practice
-Customizing Your Plots-
(2)
Use the plot command to draw a circle.
>>t=0:pi/100:2*pi; % time base
>>plot(sin(t),cos(t)); % draw circle
>>axis(square) % use same scale on both axes
57
Practice
-Customizing Your Plots-
(3)
>>t=0:0.01:1; % generate a time vector t
>>y=sin(2*pi*5*t); % define the dependent vector y
>>x=y+cos(2*pi*5*t); % define the dependent vector x
>>z=abs(y); % define the dependent vector z
>>w=1./(1+t.^2); % define the dependent vector w
>>subplot(2,2,1);plot(t,y);grid; % split screen, plot y versus t, and apply grid lines
>>ylabel(Voltage,[V]); % label the vertical axis
>>subplot(2,2,2);plot(t,x);grid; % plot x versus t, and apply grid lines
>>ylabel(Current, [A]); % label the vertical axis
>>subplot(2,2,3);plot(t,z);grid; % plot z versus t, and apply grid lines
>>ylabel(Power,[W]); % label the vertical axis
>>subplot(2,2,4);plot(t,w);grid; % plot w versus t
>>ylabel(Voltage,[V]); % label the vertical axis
Creek Letters, Subscripts, & Superscripts
A. Greek Letters
When you add labels and titles on your plot, you may want to use Greek letters,
subscripts and superscripts. To get Greek letters, simply type their names preceded
by a backslash as follows:
\alpha \beta \gamma \delta \epsilon \phi
\theta \kappa \lambda \mu \pi \rho
\sigma \tau \xi \zeta \omega
58
Practice
- Greek Letters-
>>label(H(\omaga))
You can also use capital Creek letters, like this, \Gamma
B. Subscripts
To put a subscript on a character use the underscore character on the keyboard:
1
is
coded by typing \mu_1. If the subscript is more than one character long, such as
12
,
use this: \mu_{12}.
C. Superscripts
Superscript work the same way only use the ^ character: \theta^{10} to get
10
.
- Script Files and Function Files
Introduction
MATLAB operates in two modes:
The interactive mode
The batch mode
Thus far we considered only the command-driven mode (interactive mode). Under
this mode MATLAB processes the statement and display the result immediately.
MATLAB is also able to execute (batch mode) programs that are saved in files. These
files must be in ASCII format and have an extension .m (for example prog1.m). This
is the reason why MATLAB files are called M-files. There are two types of M-files:
script files and function files.
59
Script Files
A script file is an ordinary text file that contains a sequence of MATLAB statements.
Variables in a script file are global. These files offer a more effective working
environment and allow files to be saved for future use. To execute a script file,
simply type the filename (without the extension) at the MATLAB command window.
To make a script file, I suggest you create a temporary sub-directory for all your work,
like c:\myfiles, start MATLAB and change its working directory to c:\my files, via the
cd command, as you would in DOS and UNIX. To use a floppy disk as the storage
location, which is an excellent idea since you can take your work with you when you
leave the computer lab, put a formatted floppy disk in the computer and type cd a:\ as
follows:
>>cd a:\ <enter> % change the current directory to a:
The following commands facilitate moving around directories:
>>! mkdir c:\mlab % create a sub-directory named mlab
>>!rmdir c:\mlab % remove the sub-directory mlab
>>cd c:\mlab % change the working directory to mlab
>>pwd % show current working directory
>>dir % list the contents of the current directory
>>what % list only the M-files in the current directory
>>ls % show a list of files in the working directory
>>delete filename.m % delete a specified file
>>type filename.m % print a specific file to the screen
>>which filename.m % find the current path
NOTE
In the CAEC (or ECE labs) cluster, all directories on the hard disk are write protected,
in order to avoid accumulation of files. The best practice is to use a floppy disk for
your M-files.
60
Example
-Script Files-
As an example, let us create a script file named, toto.m. The script file can created
and edited using any ASCII editor, such as notepad or the built-in MATLAB editor,
which color codes reserved words and other program elements. You bring up the
MATLAB text editor window by clicking the editor icon on the toolbar (or choose
New, then M-file under the File pull-down menu or launch it by typing edit from
within MATLAB environment). Then enter the script file in the editor window, as
follows:
After you have typed in the script file, you should save it in the newly created
sub-directory. To do this, select Save As under the File menu item from the editors
menu bar. When the save dialog box opens, type in the name toto.m and click on
save. Return to the MATLAB command window.
To run the script, simply type,
>>toto <enter>
61
If there are errors, MATLAB will beep and display error messages in the command
window. Return to the MATLAB editor to debug the original script, save the changes
and run it again. To open an existing M-file, choose Open under the File menu and
select the file for editing.
Function Files
MATLAB has many powerful built-in functions. MATLAB also allows for user to
write their own functions. Functions are identical to script files, except that variable
values may be passed into or out of the function file. The function file starts with the
keyword function and defines the function name and input and output variables. The
function file starts with the keyword function and defines the function name and input
and output variables. The format of the first statement for a function named toto is of
the form
Function [output1,output2,output3,] = toto(input1,input2,input3,)
There the input variables are enclosed within parentheses while output variables are
within square brackets if there is more than one output variable.
Example
- Function Files-
As an illustration, let us create the function magphase.m, which computes the
magnitude and phase of a complex number z supplied by the user.
Invoke the built-in MATLAB editor and enter the following lines of code:
function [m,p]=magphase(z) % specify a file as a function file
% z is a complex number supplied by the user (input variable)
% m and p are output variables representing the magnitude and phase of z
% magphase is the function name
m=abs(z);
p=angle(z)*180/pi;
% compute the magnitude of z
% compute the phase in degrees
( Continue on next page)
62
Save this function as magphase.m, and then leave the editor to return to the
command window. Be careful not to save your M-file with the same name as one
of the MATLABs functions.
We are ready to run the created function file.
>>z=2+3j; % specify and arbitrary complex number
>>magphase(z) % provide the magnitude and phase of z.
NOTE
Functions have many advantages over scripts, therefore, I recommend that you always
use functions over scripts.
Sub-functions
A sub-function is local and visible only to other functions in the same file. Defining a
new function with the function keyword, after the body of the preceding function,
creates a sub-function.
Practice
-Sub-functions-
function [mn, stdev]=stat(x)
% returns the mean and standard deviation of a supplied data vector
% mn=mean
% stdev=standard deviation
% x=data vector supplied by the user
n=length (x);
mn=avg(x,n)
stdev=sqrt(sum((x-avg(x,n)).^2)/(n-1))
function mn=avg(x,n)
mn=sum(x)/n;
63
- inline functions
You can create your own functions to use in MATLAB. If your function is simple
enough (i.e., ( )
2
3 5 f x x x = + + ), then MATLAB has a command inline used to
define the so-called inline functions in the command window. Let us say we want to
define the function ( )
2
3x
g x xe
= + + +
>>pcoeff=polyfit(x,y,n)
The output of this function is a vector pcoeff which includes the coefficients p(1),
p(2), , p(n).
B. Polyval
The polyval function uses the coefficients generated from polyfit to evaluate the
polynomial specified by pcoeff for a given set of x values
>>polyval(pcoeff, x) .
Quality of Fit
The plot of the curve that represents the fitted polynomial overlaid on the data is a
convenient way of evaluating the quality of the fit. Using the coefficients determined
by polyfit, one can create such a plot as follows:
>>coef=polyfit(x,y,n);
>>x_fit=linspace(min(x),max(x),N);
>>y_fit=polyval(pcoeff,x_fit);
>>plot(x,y,o,x_fit,y_fit)
where N=number of points used to plot the fitted polynomial
n=order of the polynomial to be fitted
81
Practice
Curve Fitting- The ployfit Command-
(1)
Find the third-order least squares regression polynomial for these data and use the
resulting model to predict the value of y for x=8.
x 1 2 3 4 5 6 7
y 2 8 26 50 140 224 350
>>x=[1 2 3 4 5 6 7];
>>y=[2 8 26 50 140 224 350];
>>p=polyfit(x,y,3) % third-order polynomial that fits the data
p =
0.5000 6.6429 -23.8571 20.8571
3 2
0.5 6.6429 23.8571 20.8571 p x x x = + +
>>val=polyval(p,8) % predict the value of y using the given model
val =
511.1429
82
Practice
Curve Fitting- The polyfit Command-
(2)
In this example we will generate the data from
2 3
40 7 y x x = + with added
random error. The random error has a gaussian distribution with zero mean and a
standard deviation of unity. We will fit a cubic polynomial to the data, then plot the
two functions on the same frame to see if the fit is any good.
x=linspace(0,8,41);
y=-40+7*x.^2-x.^3;
y=y+6*randn(size(x));
xp=0:0.02:8;
n=3;
p=polyfit(x,y,n);
yp=polyval(p,xp);
subplot(2,1,1);plot(x,y,o,xp,yp,LineWidth,2); grid
title(cubic polynomial fit)
ylabel(y)
xlabel(x)
axis([0 8 -80 60])
83
- The interpl Command
MATLAB has a built-in interpolation routine interp1. Suppose you are given a set of
data points {x,y} and you have a different set of x-values{ }
i
x for which you want to
obtain the corresponding{ }
i
y values by interpolating in the {x,y} data set. You can
accomplish this task by using one of these three flavors of the interp1. By default,
MATLAB uses linear interpolation between data points.
>>yi=interp1(x,y,xi,linear);
>>yi=interp1(x,y,xi,cubic);
>>yi=interp1(x,y,xi,spline);
% linear interpolation
% quadratic interpolation
% spline interpolation
Practice
-Interpolation: The interpl Command
%data set
>>inc=pi/5;
>>x=0:inc:2*pi;
>>y=sin(x);
>>xi=0:inc/20:2*pi;
>>%linear interpolation
>>yi=interp1(x,y,xi,yi,linear);
>>subplot(2,1,1);plot(x,y,b-xi,yi,r-);grid
>>%cubic interpolation
>>yi=interp1(x,y,xi,cubic);
>>subplot(2,1,2);plot(x,y,b-xi,yi,r-);grid
84
Introduction
Data file commands are used to save and load files in either standard ASCII text or the
more compact MATLAB binary format which uses the *.mat extension. The
binary .mat format is useful for files which will be used with MATLAB, while the
ASCII format is useful when working with other programs (such as a word processor),
or sharing data with others who may not have access to MATLAB.
Practice
-Saving & Loading of Data-
>>x=0:5;
>>y=rand(size(x));
>>[x y]
ans =
0 0.9501
1.0000 0.2311
2.0000 0.6068
3.0000 0.4860
4.0000 0.8913
5.0000 0.7621
A. The save Command
The save command will save all of the user-generated variables. To save x, and y data
in the file my_data.mat, proceed as follows:
>>save my_data x y; % create the file my_data.mat
The file my_data.mat will appear in the current directory and contains x, and y.
The use of ASCII format, -ascii or /ascii is appended after the variable names:
>>save my_data x y-ascii; % create the text file my_data.dat
85
To verify that these files are valid we first clear the MATLAB workspace and load the
file back into the workspace.
B. The Load Command
The load command is used to restore the variables at a subsequent MATLAB session:
>>load my_data % load the .mat file
>>load my_data.dat % load the ASCII file