Usman Institute of Technology
Department of Computer Science
Spring 2023
CS457 – Digital Image Processing
Lab # 01
Objective:
This experiment introduces the students to Elementary concepts of MATLAB. The
use of layout, matrices, plots and basic commands are discussed
Name of Student
Student ID
Date of Lab Conducted
Marks Obtained
Remarks
Signature
March 16, 2023 Lab 01 – MATLAB Fundamentals
Student Name: ___________________________ Roll No: ________________ Section: ______________
Lab 01: MATLAB Fundamentals
Simple Calculation, Basic Plotting and Matrix Operations.
Introduction
The name MATLAB stands for MATrix LABoratory. MATLAB was written originally to provide
easy access to matrix software developed by the LINPACK (linear system package) and EISPACK
(Eigen system package) projects.
MATLAB is a high-performance language for technical computing. It integrates computation,
visualization, and programming environment. Furthermore, MATLAB is a modern programming
language environment: it has sophisticated data structures, contains built-in editing and debugging
tools, and supports object-oriented programming. These factors make MATLAB an excellent tool for
teaching and research.
MATLAB has many advantages compared to conventional computer languages (e.g. C, FORTRAN)
for solving technical problems. MATLAB is an interactive system whose basic data element is an
array that does not require dimensioning. The software package has been commercially available
since 1984 and is now considered as a standard tool at most universities and industries worldwide.
It has powerful built-in routines that enable a very wide variety of computations. It also has easy to
use graphics commands that make the visualization of results immediately available. Specific
applications are collected in packages referred to as toolbox. There are toolboxes for signal
processing, symbolic computation, control theory, simulation, optimization, and several other fields of
applied science and engineering.
1.2 A minimum MATLAB session
The goal of this minimum session (also called starting and exiting sessions) is to learn the first steps:
1. How to log on
2. Invoke MATLAB
3. Do a few simple calculations
4. How to quit MATLAB
1.2.1 Starting MATLAB
After logging into your account, you can enter MATLAB by double-clicking on the MATLAB
shortcut icon (MATLAB 7.0.4) on your Windows desktop. When you start MATLAB, a special
window called the MATLAB desktop appears. The desktop is a window that contains other windows.
The major tools within or accessible from the desktop are:
1. The Command Window
2. The Command History
3. The Workspace
4. The Current Directory
5. The Help Browser
6. The Start button
Course Instructor: Dr. Muhammad Wasim CS 457 | Digital Image 1
Processing
March 16, 2023 Lab 01 – MATLAB Fundamentals
Student Name: ___________________________ Roll No: ________________ Section: ______________
Figure 1.1: The graphical interface to the MATLAB workspace
When MATLAB is started for the first time, the screen looks like the one that shownin the Figure 1.1.
This illustration also shows the default configuration of the MATLABdesktop. You can customize the
arrangement of tools and documents to suit your needs.
Now, we are interested in doing some simple calculations. We will assume that youhave sufficient
understanding of your computer under which MATLAB is being run.
You are now faced with the MATLAB desktop on your computer, which contains the prompt(>>) in
the Command Window. Usually, there are 2 types of prompt:
>>for full version
EDU> for educational version
Note: To simplify the notation, we will use this prompt, >>, as a standard prompt sign,though our
MATLAB version is for educational purpose.
1.2.2 Using MATLAB as a calculator
As an example of a simple interactive calculation, just type the expression you want toevaluate. Let's
start at the very beginning. For example, let's suppose you want to calculatethe expression, 1 + 2 *3.
You type it at the prompt command (>>) as follows,
>> 1+2*3
ans =
7
You will have noticed that if you do not specify an output variable, MATLAB uses adefault variable
ans, short for answer, to store the results of the current calculation. Notethat the variable ans is
created (or overwritten, if it is already existed). To avoid this, youmay assign a value to a variable or
output argument name. For example,
>> x = 1+2*3
x =
7
Course Instructor: Dr. Muhammad Wasim CS 457 | Digital Image 2
Processing
March 16, 2023 Lab 01 – MATLAB Fundamentals
Student Name: ___________________________ Roll No: ________________ Section: ______________
will result in x being given the value 1 + 2 3 = 7. This variable name can alwaysbe used to refer to
the results of the previous computations. Therefore, computing 4xwillresult in
>> 4*x
ans =
28.0000
Before we conclude this minimum session, Table 1.1 gives the partial list of arithmeticoperators.
Symbol Operation Example
+ Addition 2+3
- Subtraction 2-3
* Multiplicatio 2*3
n
/ Division 2/3
Table 1.1: Basic arithmetic operators
1.2.3 Quitting MATLAB
To end your MATLAB session, type quit in the Command Window, or select File → ExitMATLAB
in the desktop main menu.
1.3 Getting started
After learning the minimum MATLAB session, we will now learn to use some additionaloperations.
1.3.1 Creating MATLAB variables
MATLAB variables are created with an assignment statement. The syntax of variable assignment is
variable name = a value (or an expression)
For example,
>> x = expression
where expression is a combination of numerical values, mathematical operators, variables,and
function calls. On other words, expression can involve:
1. manual entry
2. built-in functions
3. user-defined functions
1.3.2 Overwriting variable
Once a variable has been created, it can be reassigned. In addition, if you do not wish tosee the
intermediate results, you can suppress the numerical output by putting a semicolon(;) at the end of the
line. Then the sequence of commands looks like this:
>> t = 5;
>> t = t+1
t =
6
1.3.3 Error messages
If we enter an expression incorrectly, MATLAB will return an error message. For example,in the
following, we left out the multiplication sign, *, in the following expression
>> x = 10;
>> 5x
??? 5x
|
Course Instructor: Dr. Muhammad Wasim CS 457 | Digital Image 3
Processing
March 16, 2023 Lab 01 – MATLAB Fundamentals
Student Name: ___________________________ Roll No: ________________ Section: ______________
Error: Unexpected MATLAB expression
1.3.4 Making corrections
To make corrections, we can, of course retype the expressions. But if the expression islengthy, we
make more mistakes by typing a second time. A previously typed commandcan be recalled with the
up-arrow key ↑. When the command is displayed at the commandprompt, it can be modified if needed
and executed.
1.3.5 Controlling the hierarchy of operations or precedence
Let's consider the previous arithmetic operation, but now we will include parentheses. Forexample, 1
+ 2 *3 will become (1 + 2) *3
>> (1+2)*3
ans =
9
and, from previous example
>> 1+2*3
ans =
7
By adding parentheses, these two expressions give different results: 9 and 7.
The order in which MATLAB performs arithmetic operations is exactly that taughtin high school
algebra courses. Exponentiations are done first, followed by multiplicationsand divisions, and finally
by additions and subtractions. However, the standard order ofprecedence of arithmetic operations can
be changed by inserting parentheses. For example,the result of 1+2*3 is quite different than the
similar expression with parentheses (1+2)*3.The results are 7 and 9 respectively. Parentheses can
always be used to overrule priority,and their use is recommended in some complex expressions to
avoid ambiguity.
Therefore, to make the evaluation of expressions unambiguous, MATLAB has established a series of
rules. The order in which the arithmetic operations are evaluated is givenin Table 1.2. MATLAB
arithmetic operators obey the same precedence rules as those inmost computer programs. For
operators of equal precedence, evaluation is from left to right.
Precedence Mathematical operations
First The contents of all parentheses are evaluated first, starting from the innermost
parentheses and working outward.
Second All exponentials are evaluated, working from left to right
Third All multiplications and divisions are evaluated, working from left to right
Fourth All additions and subtractions are evaluated, starting from left to right
Table 1.2: Hierarchy of arithmetic operations
Now, consider another example:
In MATLAB, it becomes
>> 1/(2+3^2)+4/5*6/7
ans =
0.7766
or, if parentheses are missing,
>> 1/2+3^2+4/5*6/7
ans =
10.1857
So here what we get: two different results. Therefore, we want to emphasize the importanceof
precedence rule in order to avoid ambiguity.
Course Instructor: Dr. Muhammad Wasim CS 457 | Digital Image 4
Processing
March 16, 2023 Lab 01 – MATLAB Fundamentals
Student Name: ___________________________ Roll No: ________________ Section: ______________
1.3.6 Entering multiple statements per line
It is possible to enter multiple statements per line. Use commas (,) or semicolons (;) toenter more than
one statement at once. Commas (,) allow multiple statements per linewithout suppressing output.
>> a=7; b=cos(a), c=cosh(a)
b =
0.6570
c =
548.3170
1.4 Mathematical functions
MATLAB offers many predefined mathematical functions for technical computing whichcontains a
large set of mathematical functions.
Typing help elfun and help specfun calls up full lists of elementary and specialfunctions respectively.
There is a long list of mathematical functions that are built into MATLAB. Thesefunctions are called
built-ins. Many standard mathematical functions, such as sin(x), cos(x),tan(x), ex, ln(x), are evaluated
by the functions sin, cos, tan, exp, and log respectively inMATLAB.
Table 1.3 lists some commonly used functions, where variables x and y can be numbers,vectors, or
matrices.
Syntax Function Syntax Function
cos(x) Cosine abs(x) Absolute value
sin(x) Sine sign(x) Signum function
tan(x) Tangent max(x) Maximum value
acos(x) Arc cosine min(x) Minimum value
asin(x) Arc sine ceil(x) Round towards +1
atan(x) Arc tangent floor(x) Round towards -1
exp(x) Exponential round(x) Round to nearest integer
sqrt(x) Square root rem(x) Remainder after division
log(x) Natural logarithm angle(x) Phase angle
log10(x) Common logarithm conj(x) Complex conjugate
Table 1.3: Elementary functions
In addition to the elementary functions, MATLAB includes a number of predefined constant values. A list of the most
common values is given in Table 1.4.
Values Description
pi The π number, π = 3:14159...
i,j
The imaginary unit i,
NaN Not a number
Table 1.4: Predefined constant values
1.4.1 Examples
We illustrate here some typical examples which related to the elementary functions previouslydefined.
As a first example, the value of the expression y = e-asin(x) + 10 , for a = 5, x = 2, andy = 8 is
computed by
>> a = 5; x = 2; y = 8;
>> y = exp(-a)*sin(x)+10*sqrt(y)
y =
28.2904
Course Instructor: Dr. Muhammad Wasim CS 457 | Digital Image 5
Processing
March 16, 2023 Lab 01 – MATLAB Fundamentals
Student Name: ___________________________ Roll No: ________________ Section: ______________
The subsequent examples are
>>log(142)
ans =
4.9558
>>log10(142)
ans =
2.1523
Note the difference between the natural logarithm log(x) and the decimal logarithm (base10) log10(x).
To calculate sin(π=4) and e10, we enter the following commands in MATLAB,
>>sin(pi/4)
ans =
0.7071
>>exp(10)
ans =
2.2026e+004
1.5 Basic plotting
MATLAB has an excellent set of graphic tools. Plotting a given data set or the resultsof computation
is possible with very few commands. You are highly encouraged to plotmathematical functions and
results of analysis as often as possible. Trying to understandmathematical equations with graphics is
an enjoyable and very efficient way of learning mathematics. Being able to plot mathematical
functions and data freely is the most importantstep, and this section is written to assist you to do just
that.
1.5.1 Creating simple plots
The basic MATLAB graphing procedure, for example in 2D, is to take a vector of x-coordinates, x =
(x1;...; xN), and a vector of y-coordinates, y = (y1;...; yN), locate thepoints (xi; yi), with i = 1; 2; : : : ; n
and then join them by straight lines. You need to preparex and y in an identical array form; namely, x
and y are both row arrays or column arrays ofthe same length.
The MATLAB command to plot a graph is plot(x,y). The vectors x = (1; 2; 3; 4; 5; 6)and y = (3;¡1;
2; 4; 5; 1) produce the picture shown in Figure 1.2.
>> x = [1 2 3 4 5 6];
>> y = [3 -1 2 4 5 1];
>>plot(x,y)
Note: The plot functions has different forms depending on the input arguments. If y is avector
plot(y)produces a piecewise linear graph of the elements of y versus the index of theelements of y. If
we specify two vectors, as mentioned above, plot(x,y) produces a graphof y versus x.
For example, to plot the function sin (x) on the interval [0; 2π], we first create a vector ofx values
ranging from 0 to 2¼, then compute the sine of these values, and finally plot theresult:
Figure 1.2: Plot for the vectors x and y
>> x = 0:pi/100:2*pi;
Course Instructor: Dr. Muhammad Wasim CS 457 | Digital Image 6
Processing
March 16, 2023 Lab 01 – MATLAB Fundamentals
Student Name: ___________________________ Roll No: ________________ Section: ______________
>> y = sin(x);
>>plot(x,y)
Notes:
0:pi/100:2*pi yields a vector that
o starts at 0,
o takes steps (or increments) of ¼=100,
o stops when 2πis reached.
If you omit the increment, MATLAB automatically increments by 1.
1.5.2 Adding titles, axis labels, and annotations
MATLAB enables you to add axis labels and titles. For example, using the graph from theprevious
example, add an x- and y-axis labels.
Now label the axes and add a title. The character pi creates the symbol π. Anexample of 2D plot is
shown in Figure 1.3.
Figure 1.3: Plot of the Sine function
>>xlabel('x = 0:2\pi')
>>ylabel('Sine of x')
>>title('Plot of the Sine function')
The color of a single curve is, by default, blue, but other colors are possible. The desired color is
indicated by a third argument. For example, red is selected by plot(x,y,'r'). Notethe single quotes, ' ',
around r.
1.5.3 Multiple data sets in one plot
Multiple (x; y) pairs arguments create multiple graphs with a single call to plot. For example,these
statements plot three related functions of x: y1 = 2 cos(x), y2 = cos(x), and y3 =0.5*cos(x), in the
interval 0 x 2π.
>> x = 0:pi/100:2*pi;
>> y1 = 2*cos(x);
>> y2 = cos(x);
>> y3 = 0.5*cos(x);
>>plot(x,y1,'--',x,y2,'-',x,y3,':')
>>xlabel('0 \leq x \leq 2\pi')
>>ylabel('Cosine functions')
>>legend('2*cos(x)','cos(x)','0.5*cos(x)')
>>title('Typical example of multiple plots')
>>axis([0 2*pi -3 3])
Course Instructor: Dr. Muhammad Wasim CS 457 | Digital Image 7
Processing
March 16, 2023 Lab 01 – MATLAB Fundamentals
Student Name: ___________________________ Roll No: ________________ Section: ______________
The result of multiple data sets in one graph plot is shown in Figure 1.4.
Figure 1.4: Typical example of multiple plots
By default, MATLAB uses line style and color to distinguish the data sets plotted inthe graph.
However, you can change the appearance of these graphic components or addannotations to the graph
to help explain your data for presentation.
1.5.4 Specifying line styles and colors
It is possible to specify line styles, colors, and markers (e.g., circles, plus signs, . . . ) usingthe plot
command:
plot(x,y,'style_color_marker')
where style_color_marker is a triplet of values from Table 1.5.
To find additional information, type help plot or doc plot.
Symbol Color Symbol Line Style Symbol Marker
K Black - Solid + Plus sign
R Red -- Dashed o Circle
B Blue : Dotted * Asterisk
G Green -. Dash-dot . Point
C Cyan none No line Cross
M Magenta s Square
Y Yellow d Diamond
Table 1.5: Attributes for plot
1.6 Matrix generation
Matrices are fundamental to MATLAB. Therefore, we need to become familiar with matrixgeneration
and manipulation. Matrices can be generated in several ways.
1.6.1 Entering a vector
A vector is a special case of a matrix. The purpose of this section is to show how to createvectors and
matrices in MATLAB. As discussed earlier, an array of dimension 1 * n is calleda row vector,
whereas an array of dimension m *1 is called a column vector. The elementsof vectors in MATLAB
Course Instructor: Dr. Muhammad Wasim CS 457 | Digital Image 8
Processing
March 16, 2023 Lab 01 – MATLAB Fundamentals
Student Name: ___________________________ Roll No: ________________ Section: ______________
are enclosed by square brackets and are separated by spaces or bycommas. For example, to enter a
row vector, v, type.
>> v = [1 4 7 10 13]
v =
1 4 7 10 13
Column vectors are created in a similar way, however, semicolon (;) must separate thecomponents of
a column vector,
>> w = [1;4;7;10;13]
w =
1
4
7
10
13
On the other hand, a row vector is converted to a column vector using the transpose operator.The
transpose operation is denoted by an apostrophe or a single quote (').
>> w = v'
w =
1
4
7
10
13
Thus, v(1) is the first element of vector v, v(2) its second element, and so forth.Furthermore, to access
blocks of elements, we use MATLAB's colon notation (:). For example, to access the first three
elements of v, we write,
>>v(1:3)
ans =
1 4 7
Or, all elements from the third through the last elements,
>>v(3,end)
ans =
7 10 13
where end signifies the last element in the vector. If v is a vector, writing
>>v(:)
produces a column vector, whereas writing
>>v(1:end)
produces a row vector.
1.6.2 Entering a matrix
A matrix is an array of numbers. To type a matrix into MATLAB you must
o begin with a square bracket, [
o separate elements in a row with spaces or commas (,)
o use a semicolon (;) to separate rows
o end the matrix with another square bracket, ].
Here is a typical example. To enter a matrix A, such as,
Course Instructor: Dr. Muhammad Wasim CS 457 | Digital Image 9
Processing
March 16, 2023 Lab 01 – MATLAB Fundamentals
Student Name: ___________________________ Roll No: ________________ Section: ______________
A= (1.1)
type,
>> A = [1 2 3; 4 5 6; 7 8 9]
MATLAB then displays the 3 3 matrix as follows,
A =
1 2 3
4 5 6
7 8 9
Note that the use of semicolons (;) here is different from their use mentioned earlier tosuppress output
or to write multiple commands in a single line.
Once we have entered the matrix, it is automatically stored and remembered in theWorkspace. We can
refer to it simply as matrix A. We can then view a particular element ina matrix by specifying its
location. We write,
>>A(2,1)
ans =
4
A(2,1) is an element located in the second row and first column. Its value is 4.
1.6.3 Matrix indexing
We select elements in a matrix just as we did for vectors, but now we need two indices.The element of
row i and column j of the matrix A is denoted by A(i,j). Thus, A(i,j)in MATLAB refers to the element
Aij of matrix A. The first index is the row number andthe second index is the column number. For
example, A(1,3) is an element of first row andthird column. Here, A(1,3)=3.
Correcting any entry is easy through indexing. Here we substitute A(3,3)=9 byA(3,3)=0. The result is
>>A(3,3) = 0
A =
1 2 3
4 5 6
7 8 0
Single elements of a matrix are accessed as A(i,j), where i 1 and j 1. Zero or negativesubscripts are
not supported in MATLAB.
1.6.4 Colon operator
The colon operator will prove very useful and understanding how it works is the key toefficient and
convenient usage of MATLAB. It occurs in several different forms.
Often we must deal with matrices or vectors that are too large to enter one element at a time. For
example, suppose we want to enter a vector x consisting of points(0,0.1, 0.2, . . . , 5). We can use the
command
>> x = 0:0.1:5;
The row vector has 51 elements.
Course Instructor: Dr. Muhammad Wasim CS 457 | Digital Image 10
Processing
March 16, 2023 Lab 01 – MATLAB Fundamentals
Student Name: ___________________________ Roll No: ________________ Section: ______________
1.6.5 Colon operator in a matrix
The colon operator can also be used to pick out a certain row or column. For example, the statement
A(m:n,k:l specifies rows m to n and column k to l. Subscript expressions refer to portions of a matrix.
For example,
>>A(2,:)
ans =
4 5 6
is the second row elements of A.
The colon operator can also be used to extract a sub-matrix from a matrix A.
>>A(:,2:3)
ans =
2 3
5 6
8 0
A(:,2:3) is a sub-matrix with the last two columns of A.
A row or a column of a matrix can be deleted by setting it to a null vector, [ ].
>>A(:,2)=[]
ans =
1 3
4 6
7 0
1.6.6 Creating a sub-matrix
To extract a submatrix B consisting of rows 2 and 3 and columns 1 and 2 of the matrix A, do the
following
>> B = A([2 3],[1 2])
B =
4 5
7 8
To interchange rows 1 and 2 of A, use the vector of row indices together with the colon operator.
>> C = A([2 1 3],:)
C =
4 5 6
1 2 3
7 8 0
It is important to note that the colon operator (:) stands for all columns or all rows. To create a vector
version of matrix A, do the following
>>A(:)
ans =
1
2
3
4
5
6
7
8
0
The sub-matrix comprising the intersection of rows p to q and columns r to s is denoted by A(p:q,r:s).
Course Instructor: Dr. Muhammad Wasim CS 457 | Digital Image 11
Processing
March 16, 2023 Lab 01 – MATLAB Fundamentals
Student Name: ___________________________ Roll No: ________________ Section: ______________
As a special case, a colon (:) as the row or column specific covers all entries in that row or column;
thus
o A(:,j) is the jth column of A, while
o A(i,:) is the ith row, and
o A(end,:) picks out the last row of A.
The keyword end, used in A(end,:), denotes the last index in the specified dimension. Hereare some
examples.
>> A
A =
1 2 3
4 5 6
789
>> A(2:3,2:3) >> A([1 3],[2 3])
ans = ans =
5 6 2 3
8 9 8 9
1.6.7 Deleting row or column
To delete a row or column of a matrix, use the empty vector operator, [ ].
>>A(3,:) = []
A =
1 2 3
4 5 6
Third row of matrix A is now deleted. To restore the third row, we use a technique forcreating a
matrix
>> A = [A(1,:);A(2,:);[7 8 0]]
A =
1 2 3
4 5 6
7 8 0
Matrix A is now restored to its original form.
1.6.8 Dimension
To determine the dimensions of a matrix or vector, use the command size. For example,
>>size(A)
ans =
3 3
means 3 rows and 3 columns.
Or more explicitly with,
>> [m,n]=size(A)
1.6.9 Transposing a matrix
The transpose operation is denoted by an apostrophe or a single quote ('). It flips a matrixabout its
main diagonal and it turns a row vector into a column vector. Thus,
>> A'
ans =
1 4 7
2 5 8
3 6 0
Course Instructor: Dr. Muhammad Wasim CS 457 | Digital Image 12
Processing
March 16, 2023 Lab 01 – MATLAB Fundamentals
Student Name: ___________________________ Roll No: ________________ Section: ______________
By using linear algebra notation, the transpose of m £ n real matrix A is the n £ m matrixthat results
from interchanging the rows and columns of A. The transpose matrix is denotedAT.
Course Instructor: Dr. Muhammad Wasim CS 457 | Digital Image 13
Processing
March 16, 2023 Lab 01 – MATLAB Fundamentals
Student Name: ___________________________ Roll No: ________________ Section: ______________
Programming Exercise
1. Create a logic to transform given matrix into required:
2. If of size (3x3), than find all possible sub-Matrix of size (2x2).
3. Write a script that asks for a temperature in degrees Celsius and computes the equivalent
temperature in Fahrenheit. (°C= (°F – 32) / 1.8 ).
4. Plot multi set data for:
1. Sin
2. Cos
3. Ten
Course Instructor: Dr. Muhammad Wasim CS 457 | Digital Image 14
Processing