Professional Documents
Culture Documents
Matlab PDF
Matlab PDF
Fundamental Programming
Prepared by:
Preface
This tutorial introduces the fundamental ideas for programming in MATLAB. The objective
is to help you at solving the kinds of mathematical problems that you will likely encounter as an
engineering student, as well as a researcher. It requires no prior knowledge of MATLAB or
programming experience but if you have a strong background in mathematics and computer
programming then you can quickly learn how MATLAB can help you with your course work
and design projects. However, for those of you who are just starting out learning MATLAB, then
this tutorial is for you.
Remember, it is assumed throughout all chapters that you are following along, using MATLAB
and entering all commands shown. The questions and answers of the exercises, will be given
during the workshop went off.
On completion of the workshop, participants should be able to:
Use MATLAB effectively and also being ready to explore more of MATLAB on your
own.
Contents
1
Introduction to MATLAB
What is MATLAB?
MATLAB System
Disadvantages of MATLAB
Getting Started
Starting MATLAB
Ending a Session
MATLAB Basics
Arithmetic Operations
14
16
17
Plotting in MATLAB
17
Images in MATLAB
24
Programming
25
Data Types
25
M-File Programming
27
Flow Control
30
ii
CHAPTER 1
Introduction to MATLAB
What is MATLAB?
MATLAB (short for MATrix LABoratory) is a special-purpose computer program optimized
to perform engineering and scientific calculations. It is a high-performance 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.
Typical uses include:
MATLAB is an interactive system whose basic data element is an array that does not require
dimensioning. This allows you to solve many technical computing problems, especially those
with matrix and vector formulations, in a fraction of the time it would take to write a program in
a scalar non-interactive language such as C, C++ or Fortran.
MATLAB has evolved over a period of years with input from many users. In university
environments, it is the standard instructional tool for introductory and advanced courses in
mathematics, engineering and science. In industry, MATLAB is the tool of choice for highproductivity research, development and analysis.
MATLAB features a family of application-specific solution called Toolboxes. Very
important to most users of MATLAB, toolboxes allow you to learn and apply specialized
technology. Toolboxes are comprehensive collections of MATLAB function (m-files) that
extend the MATLAB environment to solve particular classes of problems. Areas in which
toolboxes are available include signal processing, control systems, neural networks, fuzzy logic,
wavelets, image processing, simulation and many others.
MATLAB System
The MATLAB system consists of five main parts:
1. The MATLAB language. This is a high-level matrix/array language with control flow
statements, functions, data structures, input/output, and object-oriented programming
features. It allows both programming in the small to rapidly create quick and dirty
throw-away programs, and programming in the large to create complete large and
complex application programs.
2. The MATLAB working environment. This is the set of tools and facilities that you
work with as the MATLAB user or programmer. It includes facilities for managing the
variables in your workspace and importing and exporting data. It also includes tools for
developing, managing, debugging, and profiling M-files, MATLABs applications.
3. Handle Graphics. This is the MATLAB graphics system. It includes high-level
commands for two-dimensional and three-dimensional data visualization, image
processing, animation, and presentation graphics. It also includes low-level commands
that allow you to fully customize the appearance of graphics as well as to build complete
Graphical User Interfaces on your MATLAB applications.
4. The MATLAB mathematical function library. This is a vast collection of
computational algorithms ranging from elementary functions like sum, sine, cosine, and
complex arithmetic, to more sophisticated functions like matrix inverse, matrix
eigenvalues, Bessel functions, and fast Fourier transforms.
5. The MATLAB Application Program Interface (API). This is a library that allows you
to write C and Fortran programs that interact with MATLAB. It include facilities for
calling routines from MATLAB (dynamic linking), calling MATLAB as a computational
engine, and for reading and writing MAT-files.
Disadvantages of MATLAB
MATLAB has two principal disadvantages. The first is that it is an interpreted language and
therefore can execute more slowly than compiled languages. This problem can be mitigated by
properly structuring the MATLAB program, and by the use of the MATLAB compiler to
compile the final MATLAB program before distribution and general use.
The second disadvantage is cost: a full copy of MATLAB is five to ten times more expensive
than a conventional C or Fortran compiler. This relatively high cost is more than offset by then
reduced time required for an engineer or scientist to create a working program, so MATLAB is
cost-effective for businesses. However, it is too expensive for most individuals to consider
purchasing. Fortunately, there is also an inexpensive Student Edition of MATLAB, which is a
great tool for students wishing to learn the language. The Student Edition of MATLAB is
essentially identical to the full edition.
CHAPTER 2
Getting Started
Starting MATLAB
You can start MATLAB by double-clicking on the MATLAB icon or invoking the
application from the Start menu of Windows. The main MATLAB window, called the
MATLAB Desktop, will then pop-up and it will look like this:
Click in the command window to make it active. When a window becomes active, its titlebar
darkens. The >> is called the Command Prompt, and there will be a blinking cursor right after
it waiting for you to type something. You can enter interactive commands at the command
prompt (>>) and they will be executed on the spot.
As an example, lets enter a simple MATLAB command, which is the date command. Click
the mouse where the blinking cursor is and then type date and press the ENTER key. MATLAB
should then return something like this:
>> date
ans =
01-Sep-2006
Where the current date should be returned to you instead of 01-Sep-2006. Congratulation!
You have just successfully executed your first MATLAB command!
There is a much more user-friendly way to access the online help, namely via the MATLAB
Help Browser. Separate from the main desktop layout is a Help desktop with its own layout. This
utility can be launched by selecting [Help] [MATLAB Help] from the Help pull down menu.
This Help desktop has a right side which contains links to help with functions, help with
graphics, and tutorial type documentation.
Interrupting Calculations
If MATLAB is hung up in a calculation, or is just taking too long to perform an operation,
you can usually abort it by typing [CTRL + C] (that is, hold down the key labeled CTRL, and press
C).
Ending a Session
One final note, when you are all done with your MATLAB session you need to exit
MATLAB. To exit MATLAB, simply type quit or exit at the prompt. You can also click on the
special symbol that closes your windows (usually an in the upper right-hand corner). Another
way to exit is by selecting [File] [Exit MATLAB]. Before you exit MATLAB, you should be
sure to save any variables, print any graphics or other files you need, and in general clean up
after yourself.
CHAPTER 3
MATLAB Basics
a = 10
b = [1 2 3 4]
1
c = 2
3
1 2 3
d = 4 5 6
7 8 9
In MATLAB matricies are defined inside a pair of square braces ([]). Punctuation marks of a
comma (,), and semicolon (;) are used as a row separator and column separator, respectfully.
You can also use a space as a row separator, and a carriage return (the ENTER key) as a column
separator as well.
3.1415
my_vector1 =
>> my_vector1 = [1, 5, 7]
my_vector1 =
1
>> my_vector2 = [1
5
7]
my_vector2 =
my_vector2 =
1
5
7
1
5
7
Row 1
Row 2
Col 1 Col 2 Col 3
Figure 3.1: An array is a collection of data values organized into rows and columns
10
my_inc_vec1 =
my_inc_vec2 =
my_dec_vec =
[ 1 2 3 4 5 6 7]
[ 1 3 5 7]
[ 5 3 1]
NOTES: If the colon is used by itself within subscript, it refers to all the elements in a row or
column of a matrix!
11
Concatenating Matrices
Matrix concatenation is the process of joining one or more matrices to make a new matrix.
The expression C = [A B] horizontally concatenates matrices A and B. The expression C = [A;
B] vertically concatenates them.
Examples 3.3
>> A = [8 19; 7 2];
>> B = [1 64; 4 5; 3 78];
>> C = [A; B]
C =
8
7
1
4
3
19
2
64
5
78
Reshaping a Matrix
Here are a few examples to illustrate some of the ways you can reshape matrices.
Examples 3.4
Reshape 3-by-4 matrix A to have dimensions 2-by-6.
>> A = [1 4 7 10; 2 5 8 11; 3 6 9 12]
A =
1
2
3
4
5
6
7
8
9
10
11
12
>> B = reshape(A, 2, 6)
B =
1
2
3
4
5
6
7
8
9
10
11
12
12
2
5
8
11
3
6
9
12
size
length
min
max
sum
sort
abs
Examples 3.6
The following example demonstrates the use some of these functions.
>> A = [3 1 2 4];
>> szA = size(A)
mnA =
sumA =
szA =
1
1
>> mxA = max(A)
10
>> stA = sort(A)
mxA =
stA =
lenA =
4
1
13
diag
cat
ones
zeros
rand
repmat
Examples 3.7
The following example demonstrates the use some of these functions.
>> A = zeros(2,4)
>> C = rand(4,3)
A =
C =
0
0
0
0
0
0
0
0
0.9501
0.2311
0.6068
0.4860
>> B = 7*ones(1,3)
0.8913
0.7621
0.4565
0.0185
0.8214
0.4447
0.6154
0.7919
B =
7
Arithmetic Operations
MATLAB can be used to evaluate simple and complex mathematical expressions. When we
move from scalars to vectors (and matrices), some confusion arises when performing arithmetic
operations because we can perform some operations either on an element-by-element (array
operation) or matrices as whole entities (matrix operation). Expressions use familiar
arithmetic operators:
Array Operators
Operation
Addition
Subtraction
Multiplication
Division
MATLAB Form
A + B
A - B
A .* B
A ./ B
Comments
Array addition is identical
Array subtraction is identical
Element-by-element multiplication of A and B. Both
arrays must be the same shape, or one of them must
be a scalar
Element-by-element division of A and B. Both arrays
must be the same shape, or one of them must be a
scalar
14
A .^ B
Examples 3.8
The following example demonstrates the use some of these operations.
>> A = [1 2 3 4];
>> B = A.^2
B =
4
5
6
7
8
9
10
11
12
B =
2
8
2
6
10
3
7
11
16
>> A = [ 2 4 ; 8 10]
A =
>> B = [1 2 3 4; 5 6 7 8; 9 10 11 12]
1
5
9
4
8
12
4
10
>> B = [2 4; 2 5]
B =
>> C = A.*B
2
2
4
5
C =
1
10
27
8
30
60
21
56
99
>> C = A./B
C =
40
88
144
1
4
1
2
Matrix Operators
Operation
Addition
Subtraction
Multiplication
MATLAB Form
A + B
A - B
A * B
Division
A / B
Power
A ^ B
Comments
Array addition is identical
Array subtraction is identical
Matrix multiplication of A and B. The number of
columns in A must equal the number of rows in B.
Matrix division defined by A * inv(B), where
inv(B) is the inverse of matrix B.
Matrix exponentiation of A and B. The power is
computed by repeated squaring
Examples 3.9
>> A = [ 2 4 ; 8 10];
>> B = [2 4; 2 5];
>> C = A*B
C =
12
36
28
82
>> A = [ 2 4 ; 8 10];
>> B = [2 4; 2 5];
>> C = B*A
C =
36
44
48
58
15
Built-in Variables
MATLAB uses a small number of names for built-in variables. An example is the ans
variable, which is automatically created whenever a mathematical expression is not assigned to
another variable. Table below lists the built-in variables and their meanings. Although you can
reassign the values of these built-in variables, it is not a good idea to do so, because they are used
by the built-in functions.
Variable
ans
eps
i,j
pi
realmax
realmin
Inf
NaN
Meaning
Value of an expression when that expression is not assigned to a variable
Floating-point precision
Unit imaginary number, i = j = 1
, 3.14159265
Largest positive floating-point number
Smallest positive floating-point number
1
, a number larger than realmax, the result of evaluating
0
0
Not a number, (e.g., the result of evaluating
0
Examples 3.10
>> x = 0;
>> 5/x
>> x = 0;
>> x/x
16
Bytes
226
8
200
500
Class
sym object
char array
double array
double array
Calculates x
Returns the phase angle of the complex value x, in radians
Calculates ex
Remainder or modulo function
Calculates the natural logarithm loge x
Calculates the square root of x
Calculates the sin(x), with x in radians
Calculates the cos(x), with x in radians
Calculates the tan(x), with x in radians
Rounds x to the nearest integer towards positive infinity
Rounds x to the nearest integer towards zero
Rounds x to the nearest integer towards minus infinity
Rounds x to the nearest integer
Examples 3.12
>> z = 2*sin(pi/2)+log(2)
>> z = 2*sin(pi/2)+log(2)
z =
z =
2.6931
2.6931
>> z = round(z)
>> z = round(z)
z =
z =
3
17
CHAPTER 4
Plotting and Visualization
Plotting in MATLAB
MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as
annotating and printing these graphs. This section describes a few of the most important graphics
functions and provides examples of some typical applications.
Creating a Plot
The plot function has different forms, depending on the input arguments. If y is a vector,
plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements
of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x.
For example, to plot the value of the sine function from zero to 2, use:
Creating Line Plots
Examples 4.1
>> x = 0:pi/100:2*pi;
>> y = sin(x);
>> plot(x,y);
18
>>
>>
>>
>>
xlabel(Radian);
ylabel(Amplitude);
title(Plot of sin(x) vs x);
grid on;
The current limits of this plot can be determined from the basic axis function. So, in order to
modify the x-axis within [0 2], you need to run this function:
19
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y);
set(gca,XTick,-pi:pi/2:pi);
set(gca,XTickLabel,{-pi,-pi/2,0,pi/2,pi});
xlabel('-\pi \leq \Theta \leq \pi');
ylabel('sin(\Theta)');
title('Plot of sin(\Theta)');
>>
>>
>>
>>
x = linspace(0,3);
y = 10*exp(-2*x);
semilogy(x,y);
grid on;
20
Example 4.4
>> x = -pi:pi/10:pi;
>> y = tan(sin(x)) - sin(tan(x));
>> plot(x,y,'--rs','LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g','MarkerSize',10);
Multiple Plots
Often, it is desirable to place more than one plot in a single figure window. This is achieved
by three ways:
The subplot Function
The subplot Function breaks the figure window into an m-by-n matrix of small subplots and
selects the ith subplot for the current plot. The plots are numbered along the top row of the figure
window, then the second row, and so forth.
21
x = linspace(0,2*pi);
subplot(2,2,1);
plot(x,sin(x));
subplot(2,2,2)
plot(x,sin(2*x));
subplot(2,2,3)
plot(x,sin(3*x));
subplot(2,2,4)
plot(x,sin(4*x));
Multiple plots
You can assign different line styles to each data set by passing line style identifier strings to
plot and placing a legend on the plot to identify curves drawn with different symbol and line
types.
Example 4.6
>>
>>
>>
>>
>>
>>
x = linspace(0,2*pi);
y1 = sin(x);
y1 = cos(x);
y1 = tan(x);
plot(x,y1,x);
axis([0 2*pi -1 1]);
x = -pi:pi/20:pi;
y1 = sin(x);
y2 = cos(x);
plot(x,y1,'b-');
hold on;
plot(x,y2,'g--');
hold off;
legend('sin(x)','cos(x)');
22
Z = [0 : pi/50 : 10*pi];
X = exp(-.2.*Z).*cos(Z);
Y = exp(-.2.*Z).*sin(Z);
plot3(X,Y,Z,'LineWidth',2);
grid on;
xlabel('x-axis');
ylabel('y-axis');
zlabel('z-axis');
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2);
Z = sin(R)./R;
mesh(X,Y,Z);
23
Images in MATLAB
The basic data structure in MATLAB is the array, an ordered set of real or complex
elements. Thus, MATLAB stores most images as two-dimensional arrays (i.e., matrices), in
which each element of the matrix corresponds to a single pixel in the displayed image. For
example, an image composed of 200 rows and 300 columns or different colored dots would be
stored in MATLAB as a 200-by-300 matrix. Some images, such as RGB, require a threedimensional array, where the first plane in the third dimension represents the red pixel intensities,
the second plane represents the green pixel intensities, and the third plane represents the blue
pixel intensities.
This example reads an 8-bit RGB image into MATLAB and converts it to a grayscale image.
Example 4.9
>>
>>
>>
>>
>>
rgb_img = imread('ngc6543a.jpg');
image(rgb_img);
pause;
graysc_img = rgb2gray(rgb_img);
imshow(graysc_img);
24
CHAPTER 5: Programming
Data Types
CHAPTER 5
Programming
Data Types
There are many different types of data that you can work with in MATLAB. You can build
matrices and arrays of floating point and integer data, characters and strings, logical true and
false states, etc. you can also develop your own data types using MATLAB classes. Two of the
MATLAB data types, structures and cell arrays, provide a way to store dissimilar types of data in
the same array.
There are 15 fundamental data types (or classes) in MATLAB. Each of these data types is in
the form of an array. This array is a minimum of 0-by-0 in size and can grow to an n-dimensional
array of any size. Two-dimensional versions of these arrays are called matrices. All of the
fundamental data types are shown in lowercase text in the diagram below. Additional data types
are user-defined, object-oriented user classes (a subclass of structure), and java classes, that you
can use with the MATLAB interface to Java. Matrices of type double and logical may be either
full or sparse. For matrices having a small number of nonzero elements, a sparse matrix requires
a fraction of the storage space required for an equivalent full matrix. Sparse matrices invoke
special methods especially tailored to solve sparse problems.
ARRAY
(full or sparse)
logical
char
int8, unit8,
int16, uint16,
int32, uint32,
int64, uint64
NUMERIC
single
CELL
structure
Java
Classes
Function
handle
double
25
CHAPTER 5: Programming
The following table describes these data types in more detail.
Data type
int8, unit8,
int16, uint16,
int32, uint32,
int64, uint64
char
logical
single
double
cell
structure
function
handle
user class
java class
Example
Description
Signed and unsigned integer arrays that are 8, 16,
32, and 64 bits in length. Enables you to manipulate
integer quantities in a memory efficient manner.
These data types cannot be used in mathematical
operations.
'Hello'
Character array (each character is 16 bits long). This
array is also referred to as a string.
magic(4) > 10
Logical array. Must contain only logical 1 (true) and
logical 0 (false) elements. (Any nonzero values
converted to logical become logical 1.) Logical
matrices (2-D only) may be sparse.
3*10^38
Single-precision numeric array. Single precision
requires less storage than double precision, but has
less precision and a smaller range. This data type
cannot be used in mathematical operations.
3*10^300
Double-precision numeric array. This is the most
5+6i
common MATLAB variable type. Double matrices
(2-D only) may be sparse.
{17
'hello' Cell array. Elements of cell arrays contain other
eye(2)}
arrays. Cell arrays collect related data and
information of a dissimilar size together.
a.day = 12;
Structure array. Structure arrays have field names.
a.color = 'Red';
The fields contain other arrays. Like cell arrays,
a.mat = magic(3);
structures collect related data and information
together.
@humps
Handle to a MATLAB function. A function handle
can be passed in an argument list and evaluated
using feval
inline('sin(x)')
MATLAB class. This user-defined class is created
using MATLAB functions.
java.awt.Frame
Java class. You can use classes already defined in
the Java API or by a third party, or create your own
classes in the Java language.
int16(100)
26
CHAPTER 5: Programming
M-File Programming
MATLAB provides a full programming language that enables you to write a series of
MATLAB statements into a file and then execute them with a single command. You write your
program in an ordinary text file, giving the file a name of filename.m. The term you use for
filename becomes the new command that MATLAB associates with the program. The file
extension of .m makes this a MATLAB M-file. M-files can be scripts that simply execute a series
of MATLAB statements, or they can be functions that also accept arguments and produce output.
You create M-files using a text editor, then use them as you would any other MATLAB function
or command. The process looks like this:
Kinds of M-files
There are two kinds of M-files
Script M-files
Do not accept input arguments or return output
arguments
Operate on data in the workspace
Function M-files
Can accept input arguments and return output
arguments
Internal variables are local to the function by
default
Useful for automating a series of steps you Useful for extending the MATLAB language
need to perform many times
for you application
27
CHAPTER 5: Programming
Scripts
Scripts are the simplest kind of M-file because they have no input or output arguments.
They're useful for automating series of MATLAB commands, such as computations that you
have to perform repeatedly from the command line. Scripts operate on existing data in the
workspace, or they can create new data on which to operate. Any variables that scripts create
remain in the workspace after the script finishes so you can use them for further computations.
Example 5.1
% Comment lines
% Computations
% Graphics output
Try entering these commands in an M-file called petals.m. This file is now a MATLAB
script. Typing petals at the MATLAB command line executes the statements in the script.
28
CHAPTER 5: Programming
Functions
Functions are M-files that accept input arguments and return output arguments. They operate
on variables within their own workspace. This is separate from the workspace you access at the
MATLAB command prompt.
Example 5.2
function y = average(x)
% AVERAGE Mean of vector elements.
% AVERAGE(X), where X is a vector, is the mean of vector elements.
% Nonvector input results in an error.
[m,n] = size(x);
if (~((m == 1) | (n == 1)) | (m == 1 & n == 1))
error('Input must be a vector')
end
y = sum(x)/length(x);
% Actual computation
If you would like, try entering these commands in an M-file called average.m. The average
function accepts a single input argument and returns a single output argument. To call the
average function, enter
>> z = 1:99;
>> average(z)
ans =
50
29
CHAPTER 5: Programming
All MATLAB functions have a function definition line that follows this pattern.
The Function Name - MATLAB function names have the same constraints as variable
names. The name must begin with a letter, which may be followed by any combination of letters,
digits, and underscores. Making all letters in the name lowercase is recommended as it makes
your M-files portable between platforms.
Flow Control
MATLAB has several flow control constructs:
1.
2.
3.
4.
5.
6.
if
continue
break
switch and case
for
while
If
The if statement evaluates a logical expression and executes a group of statements when the
expression is true. The optional elseif and else keywords provide for the execution of alternate
groups of statements. An end keyword, which matches the if, terminates the last group of
statements. The groups of statements are delineated by the four keywords--no braces or brackets
are involved.
IF expression
statements
ELSEIF expression
statements
ELSE
statements
END
Continue
The continue statement passes control to the next iteration of the for or while loop in
which it appears, skipping any remaining statements in the body of the loop. In nested loops,
continue passes control to the next iteration of the for or while loop enclosing it.
Break
The break statement lets you exit early from a for or while loop. In nested loops, break exits
from the innermost loop only.
30
CHAPTER 5: Programming
SWITCH expression
CASE expression
statements
CASE expression
statements
OTHERWISE
statements
END
For
The for loop repeats a group of statements a fixed, predetermined number of times. A
matching end delineates the statements.
While
The while loop repeats a group of statements an indefinite number of times under control of a
logical condition. A matching end delineates the statements.
WHILE expression
Statements
END
31