Basic MATLAB Commands Practical No.: Date
Basic MATLAB Commands Practical No.: Date
Basic MATLAB Commands Practical No.: Date
Theory:
MATLAB is a mathematical and graphical software package; it has numerical, graphical, and
programming capabilities. It has built-in functions to do many operations, and there are toolboxes
that can be added to augment these functions (e.g., for signal processing). There are versions
available for different hardware platforms, and there are both professional and student editions.
In the Command Window, MATLAB can be used interactively. At the prompt, any MATLAB
command or expression can be entered, and MATLAB will immediately respond with the result.
It is also possible to write programs in MATLAB, which are contained in script files or M-files.
>> mynum = 6
mynum = 6
>>
MATLAB uses a default variable named ans if an expression is typed at the prompt and it is not
assigned to a variable. For example, the result of the expression 6 3 is stored in the variable ans:
>> 6 + 3
ans =
A short-cut for retyping commands is to press the up-arrow, which will go back to the previously
typed command(s).
Variable Names
Variable names are an example of identifier names. The rules for identifier names are:
The name must begin with a letter of the alphabet. After that, the name can contain letters,
digits, and the underscore character (e.g., value_1), but it cannot have a space.
There is a limit to the length of the name; the built-in function namelengthmax tells how
many characters this is.
MATLAB is case-sensitive. That means that there is a difference between upper- and
lowercase letters. So, variables called mynum, MYNUM, and Mynum are all different.
There are certain words called reserved words that cannot be used as variable names.
Names of built-in functions can, but should not, be used as variable names.
who shows variables that have been defined in this Command Window (this just shows the
names of the variables)
whos shows variables that have been defined in this Command Window (this shows more
information on the variables, similar to what is in the Workspace Window)
clear clears out all variables so they no longer exist
clear variablename clears out a particular variable
If nothing appears when who is entered, that means there aren’t any variables! For example, in the
beginning of a MATLAB session, variables could be created and then selectively cleared
(remember that the semicolon suppresses output):
>> who
>> mynum = 3;
>> mynum + 5;
>> who
ans mynum
The default in MATLAB is to display numbers that have decimal places with
The format command can be used to specify the output format of expressions. There are many
options, including making the format short (the default) or long. For example, changing the format
to long will result in 15 decimal places.
>> 2 * sin(1.4)
ans =
1.970899459976920
>> 3 + 55 – 62 + 4 – 5 ...
+ 22 – 1
ans =
16
Operators
There are in general two kinds of operators: unary operators, which operate on a single value or
operand; and binary operators, which operate on two values or operands. The symbol “–”, for
example, is both the unary operator for negation and the binary operator for subtraction.
Here are some of the common operators that can be used with numeric expressions:
– negation, subtraction
* multiplication
Operator Precedence Rules: Some operators have precedence over others. For example, in the
expression 4 5 * 3, the multiplication takes precedence over the addition, so first 5 is multiplied
by 3, then 4 is added to the result. Using parentheses can change the precedence in an expression:
>> 4 + 5 * 3
ans =19
Types
MATLAB supports many types of values, which are called classes. A class is essentially a
combination of a type and the operations that can be performed on values of that type. For example,
there are types to store different kinds of numbers. For float or real numbers, or in other words
numbers with a decimal place (e.g., 5.3), there are two basic types: single and double. The name
of the type double is short for double precision; it stores larger numbers than single. MATLAB
uses a floating point representation for these numbers. For integers, there are many integer types
(e.g., int8, int16, int32, and int64).
>> intmin(‘int8’)
ans =
–128
>> intmax(‘int8’)
ans =
127
>> rand
ans =
0.9501
>> rand
ans =
0.2311
The seed for the rand function will always be the same each time MATLAB is started, unless the
state is changed, for example, by the following: rand(‘state’, sum(100*clock))
This uses the current date and time that are returned from the built-in clock function to set the seed.
To generate a random real number in the range from low to high, first create the variables low and
high. Then, use the expression rand*(high–low) low. For example, the sequence
>> low = 3;
>> high = 5;
>> rand*(high–low)+low would generate a random real number in the range from 3 to 5.
Convert the character ‘a’ to its numeric equivalent, the following statement could be used:
numequiv = 97
ans = b
>> ‘a’ + 2
ans = 99
>> double(‘abcd’)
ans = 97 98 99 100
>> char(‘abcd’+ 1)
ans = bcde
Exercises:
Review Questions:
1. What is MATLAB?
2. Explain fundamental steps in digital image processing.
Theory:
In this practical, we will understand the fundamentals related to matrix. Vectors and matrices are
used to store sets of values, all of which are the same type. A vector can be either a row vector or
a column vector. A matrix can be visualized as a table of values. The dimensions of a matrix are r
× c, where r is the number of rows and c is the number of columns. This is pronounced “r by c.” If
a vector has n elements, a row vector would have the dimensions 1 × n, and a column vector would
have the dimensions n × 1. A scalar (one value) has the dimensions 1 × 1. Therefore, vectors and
scalars are actually just subsets of matrices.
The scalar is 1 × 1, the column vector is 3 × 1 (3 rows by 1 column), the row vector is 1 × 4 (1 row
by 4 columns), and the matrix is 3 × 3. All the values stored in these matrices are stored in what
are called elements. MATLAB is written to work with matrices; the name MATLAB is short for
“matrix laboratory.” For this reason, it is very easy to create vector and matrix variables, and there
are many operations and functions that can be used on vectors and matrices.
There are several ways to create row vector variables. The most direct way is to put the values that
you want in the vector in square brackets, separated by either spaces or commas. For example,
both of these assignment statements create the same vector v:
>> v = [1 2 3 4]
v=1234
>> v = [1, 2, 3, 4]
v=1234
The colon operator can be used to iterate through these values. For example, 1:5 results in all the
integers from 1 to 5:
vec = 1 2 3 4 5
Note that in this case, the brackets [ ] are not necessary to define the vector. With the colon
operator, a step value can also be specified with another colon,
One way to create a column vector is by explicitly putting the values in square brackets,
separated by semicolons:
>> c = [1; 2; 3; 4]
c=
Declaring matrices:
There is no need to declare variables; new variables are simply introduced as they are required.
A = [1 2 3; 4 5 6; 7 8 9]
1 2 3
A= 4 5 6
7 8 9
No spaces
B = zeros(3,3)
0 0 0
B= 0 0 0
0 0 0
The colon(:) is one of the most useful operator in MATLAB. It is used to create vectors, subscript
arrays, and specify for iterations.
If you want to create a row vector, containing integers from 1 to 10, you write −1:10
Format Purpose
A(:,:) is the equivalent two-dimensional array. For matrices this is the same as A.
A(:) is all the elements of A, regarded as a single column. On the left side of an
assignment statement, A(:) fills A, preserving its shape from before. In this
case, the right side must contain the same number of elements as A.
Example:
A = [1 2 3 4; 4 5 6 7; 7 8 9 10]
A(:,2:3) % second and third column of A
A(:,2) % second column of A
A(:,2:3) % second and third column of A
A(2:3,2:3) % second and third rows and second and third columns
A=
1 2 3 4
4 5 6 7
7 8 9 10
ans =
2
5
8
ans =
2 3
5 6
8 9
ans =
5 6
8 9
Function Purpose
To plot the graph of a function, you need to take the following steps −
Define x, by specifying the range of values for the variable x, for which the function is to be plotted
Following example would demonstrate the concept. Let us plot the simple function y = x for the
range of values for x from 0 to 100, with an increment of 5.
x = [0:5:100];
y = x;
plot(x, y)
MATLAB allows you to add title, labels along the x-axis and y-axis, grid lines and also to adjust
the axes to spruce up the graph.
The xlabel and ylabel commands generate labels along x-axis and y-axis.
The grid on command allows you to put the grid lines on the graph.
The axis equal command allows generating the plot with the same scale factors and the
spaces on both axes.
Exercises:
Review Questions:
1. Write short notes on sampling and quantization.
Theory:
MATLAB provides following types of loops to handle looping requirements. Click the following
links to check their detail –
While loop: Repeats a statement or group of statements while a given condition is true. It tests
the condition before executing the loop body.
while <expression>
<statements>
end
The while loop repeatedly executes program statement(s) as long as the expression remains true.
An expression is true when the result is nonempty and contains all nonzero elements (logical or
real numeric). Otherwise, the expression is false.
For loop: Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax
<program statements>
end
Nested loops: You can use one or more loops inside any another loop. MATLAB allows to use
one loop inside another loop. Following section shows few examples to illustrate the concept.
Syntax: The syntax for a nested for loop statement in MATLAB is as follows −
for m = 1:j
for n = 1:k
<statements>;
end
end
while <expression1>
while <expression2>
<statements>
end
end
Break statement: break exits only from the loop in which it occurs. Control passes to the
statement following the end of that loop.
a = 10;
while (a < 20 )
a = a + 1;
break;
end
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Exercises:
Review Questions:
1. Discuss types of adjacency between pixels with example.
Theory:
If name of the image file is test.bmp and if it is in /home/chv folder above commands can be written
as: myImage=imread(‘/home/chv/test.bmp’)
The image filename can be given as a full file path or as a file path relative to the SciLab current
directory. The current directory can be changed from the main SciLab interface window or by cd
(change directory command). The supported file formats include ‘bmp’, ‘gif’, ‘jpg’ and ‘png’.
Displaying image
After reading image data using above function, we can display images in SciLab using imshow
function. This function simply takes the array storing the image values as its only parameter.
Syntax:
imshow(<variable name>)
Example:
imshow(myImage);
1. A = importdata(filename)
2. A = importdata('-pastespecial')
Loads data from the system clipboard rather than from a file.
3. A = importdata( , delimiterIn)
Interprets delimiterIn as the column separator in ASCII file, filename, or the clipboard data. You
can use delimiterIn with any of the input arguments in the above syntaxes.
Loads data from ASCII file, filename, or the clipboard, reading numeric data starting from line
headerlinesIn+1.
Returns the detected delimiter character for the input ASCII file in delimiterOut and the detected
number of header lines in headerlinesOut, using any of the input arguments in the previous
syntaxes.
Image resizing
imresize(Image,{Parameters});
For example:
Consider that we read the image in variable myImage using imread function than we can resize
the image stored in this variable by following command
imresize(myImage,[256,256],’nearest’);
This command will convert image of any size into image of 256x256 using nearest neighbor
technique.
Color image can be converted into Grayscale image by matlab function rgb2gray.
Example: myGrayImage=rgb2gray(myImage)
Color image can be converted into Binary image using function im2bw:
Example: myBWImage=im2bw(myImage)
Drawing of intensity profile along single line on given image (Scan one line along the image and
draw intensity values (1-D signal)) can be done by function improfile()
Example: improfile(myImage,[0,150],[200,150]);
If we read given color image using imread() function, we get 3-D matrix. To separate out R,G
and B planes, we can read each plane separately as follows:
Example:
myImage=imread(‘RGBBar.bmp’);
RED=myImage(:,:,1);
GREEN=myImage(:,:,2);
BLUE=myImage(:,:,3);
If we have three R,G and B planes separately and if we want to create color image from it, we
can use concatenate function: Example:
newImage=cat(3,RED,BLUE,GREEN)
Exercises:
Review Questions:
1. Explain how zooming and interpolation method work in images.
Theory:
In Spatial domain Image processing, there are two ways: Point processing (Single pixel is
processed at a time). Neighborhood processing (Mask processing) Convolution of 3x3 or 5x5 or
other size of mask with image
S=0 if r ≤ m
S=255 if r > m
Where m=threshold
if(y(i,j)>T)
y(i,j)=255;
else
y(i,j)=0;
end
end
end
figure;
imshow(y);
Run above program for different threshold values and find out optimum threshold value for which
you are getting better result.
Horizontal flipping:
% Read in an image
filename=input('Enter file name: ','s'); imagedata = imread(filename); if(ndims(imagedata)==3)
imagedata=rgb2gray(imagedata);
Negative Image:
Negative Image can be obtained by subtracting each pixel value from 255.
255
s
s = 255-r
r 255
end
%Display original and negative images
subplot(2,1,1); imshow(img);
subplot(2,1,2); imshow(neg_img,[]);
Contrast Stretching
Contrast Stretching means Darkening level below threshold value m and whitening level above
threshold value m. This technique will enhance contrast of given image. Thresholding is example
of extreme constrast stretching.
Practically contrast stretching is done by piecewise linear approximation of graph shown in left by
following equations:
s = x.r 0 ≤ r<a
s = y.r a ≤ r<b
s = z.r b ≤ r<255
for j=1:col
if(img(i,j)<=a)
newimg(i,j)=img(i,j);
end
if (img(i,j)>a && img(i,j)<=b)
newimg(i,j)=2*img(i,j);
end
if(img(i,j)>b)
newimg(i,j)=img(i,j);
end
end
end
subplot(2,1,1); imshow(uint8(img)); subplot(2,1,2); imshow(uint8(newimg));
1. Write image processing programs using point processing method to obtain negative image,
inverse image, log image and gamma image.
Review Questions:
Theory:
Arithmetic operations like image addition, subtraction, multiplication and division is possible. If
there is two images I1 and I2 then addition of image can be given by:
Where I(x,y) is resultant image due to addition of two images. x and y are coordinates of image.
Image addition is pixel to pixel. Value of pixel should not cross maximum allowed value that is
255 for 8 bit grey scale image. When it exceeds value 255, it should be clipped to 255.
To increase overall brightness of the image, we can add some constant value depending on
brightness required. In example program we will add value 50 to the image and compare brightness
of original and modified image.
To decrease brightness of image, we can subtract constant value. In example program, value 100
is subtracted for every pixel. Care should be taken that pixel value should not less than 0 (minus
value). Subtract operation can be used to obtain complement (negative) image in which every pixel
is subtracted from maximum value i.e. 255 for 8 bit greyscale image.
Multiplication operation can be used to mask the image for obtaining region of interest. Black and
white mask (binary image) containing 1s and 0s is multiplied with image to get resultant image.
To obtain binary image function im2bw() can be used. Multiplication operation can also be used
to increase brightness of the image
Division operation results into floating point numbers. So data type required is floating point
numbers. It can be converted into integer data type while storing the image. Division can be used
to decrease the brightness of the image. It can also used to detect change in image.
while k<5,
for i = 1:Rows
for j = 1:Cols
if k==1
if k==2
newimage(i,j)=myimage(i,j)-50;
end
if k==3
newimage(i,j)=myimage(i,j)+50;
end
if k==4
newimage(i,j)=myimage(i,j)+50;
end
end
end
subplot(2,2,k); imshow(newimage,[]); k=k+1;
end
Result:
end
average=total/(Rows*Cols)
Exercises:
Review Questions:
1. Explain arithmetic coding and Huffman coding.
Theory:
Histogram is bar-graph used to profile the occurrence of each gray level in the
image
Where rk is kth grey level and nk is number of pixel having that grey level
Histogram can tell us whether image was scanned properly or not. It gives us idea
about tonal distribution in the image.
Histogram equalization can be applied to improve appearance of the image
Histogram also tells us about objects in the image. Object in an image
have similar gray levels so histogram helps us to select threshold value for object
detection.
Pseudo code:
Calculate histogram
Loop over ROWS of the image
data(i,j) = (Dm/area)*sum_of_hist(k)
End COLS oop
End ROWS Loop
Standard MATLAB function for histogram and histogram equalization:
[1] imhist function
myimage=imread(‘tier.jpg’)
imhist(myimage);
myimage = imread(‘rice.bmp’);
newimage= histeq(myimage);
Exercises:
Review Questions:
1. What is meant by histogram equalization?
Theory:
Morphological image processing is a technique introducing operations for transforming images in
a special way which takes image content into account. The most common morphological
operations are minimum (also known as dilation) and maximum (erosion) filters. The minimum
filter extends object boundaries, whereas the maximum filter erodes shapes on the image.
In morphological filters, each pixel is updated based on comparing it against surrounding pixels in
the running window. The running window is an image area around a current pixel with a defined
radius. For example, if we specify the radius = 1, the running window will be a 3x3 square around
the target pixel.
Exercises:
1. Write programs for image morphological operations using Minimum, maximum and average
filter.
Review Questions:
1. Explain various noise model and how it can be defined?
2. Explain various spatial filter used in image restoration in detail.
Theory:
Laplacian filters are derivative filters used to find areas of rapid change (edges) in images. Since
derivative filters are very sensitive to noise, it is common to smooth the image (e.g., using a
Gaussian filter) before applying the Laplacian. This two-step process is call the Laplacian of
Gaussian (LoG) operation.
There are different ways to find an approximate discrete convolution kernal that approximates the
effect of the Laplacian. A possible kernel is
This is called a negative Laplacian because the central peak is negative. It is just as appropriate to
reverse the signs of the elements, using -1s and a +4, to get a positive Laplacian. It doesn't matter.
To include a smoothing Gaussian filter, combine the Laplacian and Gaussian functions to obtain a
single equation:
When using the filter given above, or any other similar filter, the output can contain values that
are quite large and may be negative, so it is important to use an image type that supports negatives
and a large range, and then scale the output. (ImageJ has a 32-bit floating point representation).
Alternatively, a scaling factor can be used on the filter to restrict the range of values.
The median filter is a nonlinear digital filtering technique, often used to remove noise from an
image or signal. Such noise reduction is a typical pre-processing step to improve the results of later
processing (for example, edge detection on an image). Median filtering is very widely used in
digital image processing because, under certain conditions, it preserves edges while removing
noise (but see discussion below), also having applications in signal processing.
Exercises:
1. Write a program to perform image restoration methods using Laplacian filter and Median
filter.
Review Questions:
1. Explain Laplacian and Median filter in detail.
Theory:
Spatial Filtering is sometimes also known as neighborhood processing. Neighborhood processing
is an appropriate name because you define a center point and perform an operation (or apply a
filter) to only those pixels in predetermined neighborhood of that center point. The result of the
operation is one value, which becomes the value at the center point's location in the modified
image. Each point in the image is processed with its neighbors. The general idea is shown below
as a "sliding filter" that moves throughout the image to calculate the value at the center location.
In spatial filtering, we perform convolution of data with filter coefficients. In image processing,
we perform convolution of 3x3 filter coefficients with 2-D image data. In signal processing, we
perform convolution of 1-D data with set of filter coefficients.
k=length(y)
for z=n+1:n+k-1
x(z)=0;
end
for u=k+1:n+k-1
y(u)=0;
end
for i=1:n+k-1
s(i)=(x(j)*y(i-j+1))+s(i)
end
end
subplot(3,1,1)
plot2d3(x)
subplot(3,1,2)
plot2d3(y)
subplot(3,1,3)
plot2d3(s)
Take value of x: [ 1 2 3 4 5 6 7 8 9 0 10 11 12 13 14 15]
Y: [-1 1]
Observe result of convolution and write your comments:
Program for 2D convolution:
clear;
clc;
for c = 1:xcols-1
sum=0;
for a=0:yrows
for b=0:ycols
sum=sum+x(r+a,c+b)*y(a+1,b+1);
end
end
end
Enter following 2D matrix for x:
10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10
1 1 1
0 0 0
1 1 1
Exercises:
1. Write a program to remove noise using any spatial filters (Use 3x3 Mask for low pass filter or
high pass filter).
Review Questions:
1. Explain sharpening filters in detail.
2. Write down the outputs after observation of above convolution methods.