Lab Manual 1
Lab Manual 1
Lab Manual 1
COMPUTER GRAPHICS
&
IMAGE PROCESSING
LAB MANUAL 1
MATLAB TUTORIAL
MATLAB (matrix laboratory)
Online help is available from the Matlab prompt (a double arrow), both generally (listing all available
commands):
>> help
[a long list of help topics follows]
and for specific commands:
>> help fft
[a help message on the fft function follows].
Paper documentation is on the document shelf in compact black books and locally generated tutorials
are available and are used in courses.
How to quit Matlab
The answer to the most popular question concerning any program is this: leave a Matlab session by
typing
quit
or by typing
exit
to the Matlab prompt.
This is the basic introduction to Matlab. Creation of vectors is included with a few basic operations.
Topics include the following:
1. Defining a vector
2. Accessing elements within a vector
Defining a Vector
Matlab is a software package that makes it easier for you to enter matrices and vectors, and
manipulate them. The interface follows a language that is designed to look a lot like the notation use in
linear algebra.
In the text that follows, any line that starts with two greater than signs (>>) is used to denote the
matlab command line(also known as prompt). This is where you enter your commands.
Computer Graphics & Image Processing 7 th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
Almost all of Matlab's basic commands revolve around the use of vectors. A vector is defined by placing
a sequence of numbers within square braces:
>> v = [3 1]
v =
3 1
This creates a row vector which has the label "v". The first entry in the vector is a 3 and the second
entry is a 1. Note that matlab printed out a copy of the vector after you hit the enter key. If you do not
want to print out the result put a semi-colon at the end of the line:
>> v = [3 1];
>>
>> v
v=
3 1
Notice, though, that this always creates a row vector. If you want to create a column vector you need
to take the transpose of a row vector. The transpose is defined using an apostrophe ("'"):
v=
3
1
7
-21
5
6
A common task is to create a large vector with numbers that fit a repetitive pattern. Matlab can define
a set of numbers with a common increment using colons. For example, to define a vector whose first
entry is 1, the second entry is 2, the third is three, up to 8 you enter the following:
>> v = = [1:8]
v=
1 2 3 4 5 6 7 8
If you wish to use an increment other than one that you have to define the start number, the value of
the increment, and the last number. For example, to define a vector that starts with 2 and ends in 4
with steps of .25 you enter the following:
>> v = [2:.25:4]
v=
Columns 1 through 7
Columns 8 through 9
3.7500 4.0000
Accessing elements within a vector
You can view individual entries in this vector. For example to view the first entry just type in the
following:
>> v(1)
ans =
This command prints out entry 1 in the vector. Also notice that a new variable called ans has been
created. Any time you perform an action that does not include an assignment matlab will put the label
ans on the result.
A basic introduction to defining and manipulating matrices is given here. It is assumed that you know
the basics on how to define and manipulate vectors using matlab.
Defining Matrices
Defining a matrix is similar to defining a vector. To define a matrix, you can treat it like a column of
row vectors (note that the spaces are required!):
>> A = [ 1 2 3; 3 4 5; 6 7 8]
A=
1 2 3
3 4 5
6 7 8
B=
1 2 3
2 4 5
3 7 8
If you have been putting in variables through this and the tutorial on vectors, then you probably have
a lot of variables defined. If you lose track of what variables you have defined, the whos command will
let you know all of the variables you have in your work space.
>> whos
Name Size Bytes Class
You can work with different parts of a matrix, just as you can with vectors. Again, you have to be
careful to make sure that the operation is legal.
>> A(1:2,3:4)
??? Index exceeds matrix dimensions.
>> A(1:2,2:3)
ans =
2 3
4 5
>> A(1:2,2:3)'
ans =
2 4
3 5
Finally, sometimes you would like to clear all of your data and start over. You do this with the "clear"
command. Be careful though, it does not ask you for a second opinion and its results are final.
>> clear
>> whos
Loops
With loop control statements, you can repeatedly execute a block of code, looping back through the
block while keeping track of each iteration with an incrementing index variable.
For Loop
The for loop executes a statement or group of statements a predetermined number of times.
The default increment is 1. You can specify any increment, including a negative one. For positive
indices, execution terminates when the value of the index exceeds the end value; for negative
increments, it terminates when the index is less than the end value.
for m = 1:5
for n = 1:100
A(m, n) = 1/(m + n - 1);
end
end
while Loop
The while loop executes a statement or group of statements repeatedly as long as the controlling
expression is true (1).
Its syntax is
while expression
statements
end
If the expression evaluates to a matrix, all its elements must be 1 for execution to continue. To reduce
a matrix to a scalar value, use the all and any functions.
For example, this while loop finds the first integer n for which n! (n factorial) is a 100-digit number. n
= 1;
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.
The example below shows a continue loop that counts the lines of code in the file, magic.m, skipping
all blank lines and comments. A continue statement is used to advance to the next line in magic.m
without incrementing the count whenever a blank line or comment line is encountered.
Break
The break statement terminates the execution of a for loop or while loop. When a break statement is
encountered, execution continues with the next statement outside of the loop. In nested loops, break
exits from the innermost loop only.
The example below shows a while loop that reads the contents of the file fft.m into a MATLAB character
array. A break statement is used to exit the while loop when the first empty line is encountered. The
resulting character array contains the M-file help for the fft program. fid = fopen('fft.m', 'r');
s = '';
while ~feof(fid)
line = fgetl(fid);
if isempty(line)
break
end
s = strvcat(s, line);
end
disp(s)
Plotting
plot Linear 2-D plot Syntaxplot(Y)
plot(X1,Y1,...)
plot(X1,Y1,LineSpec,...)
Description:
plot(Y) plots the columns of Y versus their index if Y is a real number. If Y is complex, plot(Y) is equivalent to
plot(real(Y),imag(Y)). In all other uses of plot, the imaginary component is ignored.
plot(X1,Y1,...) plots all lines defined by Xn versus Yn pairs. If only Xn or Yn is a matrix, the vector is plotted versus the
rows or columns of the matrix, depending on whether the vector's row or column dimension matches the matrix.
plot(X1,Y1,LineSpec,...) plots all lines defined by the Xn,Yn,LineSpec triples, where LineSpec is a line specification that
determines line type, marker symbol, and color of the plotted lines.
Cycling Through Line Colors and Styles
By default, MATLAB resets the ColorOrder and LineStyleOrder properties each time you call plot. If you want changes you
make to these properties to persist, then you must define these changes as default values.
For example, set(0,'DefaultAxesColorOrder',[0 0 0],...
'DefaultAxesLineStyleOrder','-|-.|--|:')
sets the default ColorOrder to use only the color black and sets the LineStyleOrder to use solid, dash-dot, dash-dash, and
dotted line styles.
Prevent Resetting of Color and Styles with hold all
The all option to the hold command prevents the ColorOrder and LineStyleOrder from being reset in subsequent plot
commands. In the following sequence of commands, MATLAB continues to cycle through the colors defined by the axes
ColorOrder property. plot(rand(12,2))
hold all
plot(randn(12,2))
Examples
Specifying the Color and Size of MarkersYou can also specify other line characteristics using graphics properties (see line for
a description of these properties): LineWidth -- Specifies the width (in points) of the line. MarkerEdgeColor -- Specifies the
color of the marker or the edge color for filled markers (circle, square, diamond, pentagram, hexagram, and the four
triangles). MarkerFaceColor -- Specifies the color of the face of filled markers. MarkerSize -- Specifies the size of the marker
in units of points. For example, these statements, x = -pi:pi/10:pi;
y = tan(sin(x)) - sin(tan(x));
plot(x,y,'--rs','LineWidth',2,'MarkerEdgeColor','k','MarkerFaceColor','g','MarkerSize',10)
produce this graph.
Subplot
You can also use the colon operator to specify multiple locations if they are in sequence.
subplot(2,2,1:2) subplot(2,2,3) subplot(2,2,4)
if evaluates a logical expression and executes a group of statements based on the value of the
expression. In its simplest form, its syntax is
if logical_expression
statements
end
If the logical expression is true (1), MATLAB executes all the statements between the if and end lines.
It resumes execution at the line following the end statement. If the condition is false (0), MATLAB skips
all the statements between the if and end lines, and resumes execution at the line following the end
statement.
For example,
if rem(a, 2) == 0
disp('a is even')
b = a/2;
end
switch executes certain statements based on the value of a variable or expression. Its basic form is
switch expression (scalar or string)
case value1
statements % Executes if expression is value1
case value2
statements % Executes if expression is value2
.
.
.
otherwise
statements % Executes if expression does not
% match any case
End