Unit2pdf__2021_07_16_12_29_18
Unit2pdf__2021_07_16_12_29_18
CE/IT
Relational
Operator
Logical operators perform logical operations and output the result
in Boolean state true or false using the numbers 1 and 0,
respectively.
Logical
Operators
Element wise
The following functions execute bit-wise logical operations on
nonnegative integer inputs. Inputs may be scalar or in arrays.
The examples are present in the following table use scalar inputs A
and B
A = 28; % binary 11100
Logical B = 21; % binary 10101
Operators
Bit-Wise
Operator
The following operators execute AND and OR operations on
logical expressions, including scalar values. They are short-
circuiting operators in that they calculate their second operand
Logical only when the first operand does not fully determine the output.
Operators
Short-Circuit
Operators
Symbol Symbol name Role
. Dot or period Element wise operation
Object property or method specifier
… ellipsis Line continuation
, Comma Separator
: Colon Vector creation
Indexing
For loop Iteration
Matlab Special ; Semicolon Signify end of the row
Characters Suppress output of code line
() Parentheses Operator precedence
Function argument enclosure
Indexing
[] Square brackets Array concatenation
Array construction
Empty matrix and array element
deletion
{} Curly brackets Cell array assignment and contents
Symbol Symbol name Role
% Percent Comment
Conversion specifier
elseif- else
Statements
else...end end
statement discr = b*b - 4*a*c;
if discr < 0
disp('Warning: discriminant is negative, roots are imaginary');
elseif discr == 0
disp('Discriminant is zero, roots are repeated')
else
disp('Roots are real')
end
The switch is another type of conditional statement and executes one
of the group of several statements.
If we want to test the equality against a pre-defined set of rules, then
the switch statement can be an alternative of the if statement.
Syntax:
switch switch expression
case case_expression1
MATLAB Statements
switch case case_expression2
Statements
case case_expressionN
Statements
otherwise
Statements
end
Similar to if block, the switch block tests each case until one of the
case_expression is true. It is evaluated as:
case & switch must be equal for numbers as- case_expression ==
switch_expression.
For character vectors, the result returned by the strcmp function
must be equal to 1 as - strcmp(case_expression,
MATLAB switch_expression) == 1.
switch For object, case_expression == switch_expression.
For a cell array, at least one of the elements of the cell array in
case_expression must match switch_expression.
switch statement doesn't test for inequality, so a case_expression
cannot include relational operators such as < or > for comparison
against the switch_expression.
a = input('enter a number : ')
switch a
case 1
disp('Monday')
case 2
disp('Tuesday')
case 3
disp('Wednesday')
MATLAB case 4
disp('Thursday')
switch case 5
disp('Friday')
case 6
disp('Saturday')
case 7
disp('Sunday')
otherwise
disp('not a weekday')
end
A loop statement allow us to execute a statement or group of
statements multiple times.
MATLAB provides different types of loops to handle looping
requirements, including while loops, for loops, and nested loops. If
we are trying to declare or write our own loops, we need to make
sure that the loops are written as scripts and not directly in the
Command Window.
MATLAB Two additional command, break and continue, can be used to
create a third type of loop, known as midpoint break loop.
Loops Midpoint break loop is useful for situations where the commands
in the loop must be executed at least once, but where the decision
to exit the loop is based on some criterion.
Types of Loops
There are two types of loop in MATLAB.
1. for
2. while
for loop
A for loop is used to repeat a statement or a group of statements for a
fixed number of times.
Syntax:
for index = values
<program statements>
MATLAB end
while loop
Loops A while loop is used to execute a statement or a group of statements
for an indefinite number of times until the conditional specified by
while is no longer satisfied.
Syntax:
while <expression>
<statements>
end
for a = 10:20
fprintf('value of a: %d\n', a);
end
MATLAB
Loops a = 10;
Example % while loop execution
while( a <= 20 )
fprintf('value of a: %d\n', a);
a = a + 1;
end
Syntax:
for m = 1:j
for n = 1:k
<statements>;
...
end
MATLAB end
Nested Loop Syntax:
while <expression1>
while <expression2>
<statements>
end
end
All types of data variables are stored as multidimensional arrays,
let it be a character, string, or numbers.
A two-dimensional array is called a matrix often used for linear
algebra.
Array creation in MATLAB
Matrices and We can create arrays in multiple ways in MATLAB:
Arrays in By using space in between elements:
MATLAB A-= [ 3 5 7 8];
By using comma in between elements:
A= [3,5,7,8];
This command will create an array variable ‘A' having one row and
four columns.
The array having its elements in a single row is known as a row
vector. Or we can say a single-dimensional array is a vector.
A two-dimensional array is called a matrix. It means a matrix has
multiple rows and columns. So, while creating a matrix with
multiple rows, we have to separate the rows with semicolons.
Matrices and
Arrays in
MATLAB
Be careful while creating a matrix, each row should have the same
number of columns, and each row should be separated with a
semicolon. Otherwise, it will show error and won't create the
matrix.
We can create a matrix by using the in-built function, such as ones,
zeros, or rand.
Matrices and
Arrays in
Array operations are operations implemented between arrays on
MATLAB an element-by-element basis. That is, the operation is
implemented on corresponding elements in the two arrays.
The number of row and columns in both arrays must be the
same. If not, MATLAB will generate an error message.
Array operations may also appear between an array and a scalar. If
the operation is performed between an array and a scalar, the
value of the scalar is applied to every element of the array.
Matrix
Operations
Arithmetic
Operations
Examples of
Matrix and
Array
Operations
Format
command
Concatenation
of Array
Concatenation
of Array
Denoting
Complex
number
Every variable is an array in MATLAB. And all the elements in the array
are indexed as per row and column. Any particular element can be
accessed using indexing in MATLAB. The indexing in arrays in
MATLAB is the same as mathematics. It has a different syntax of
accessing the elements.
There are several ways of indexing elements in MATLAB.
1. By specifying row and column subscripts:
The most common way to refer particular components of an array is
by specifying row and column subscripts in brackets with an array
Accessing variable.
The element s searched at the intersection point of row and column
elements of specified as the subscript.
Matrix
2. Linear Indexing in MATLAB:
The use of single subscript in-spite-of row and column subscript is
called Linear Indexing in MATLAB.
An element is searched traversing down each column in order.
Accessing
elements of
Matrix
3. Refer multiple elements of an Array in MATLAB:
There is one colon operator (:) in MATLAB, use it to refer multiple
elements of an array.
Accessing
elements of
Matrix
By using the colon operator, we can create an equally spaced
vector of values. We can assign step value that can affect the next
value at a fixed interval.
Syntax: start: step: end.
Example:
Let's create a table of 13 with the help of the colon operator.
Vector
Creation Using
Colon
Operator
We can access elements only within the current dimension. It
means if it is a vector and holds nine elements, then, we can't
access the element at position 12. Because the 12th position was
not defined during the vector creation.
Accessing If we enter a command for accessing an element outside its'
current dimension, then it will throw an error saying index exceeds
Array array bounds.
Elements But we can assign a value to the position which is currently not
available.
Outside For example, we have a vector of 9 elements; then, we can create
Current a 12th element or any element beyond the 9th by assigning it the
value.
Dimension And if there is any gap between the last index and the newly
created index, then the gap index will be assigned a 0 value
automatically.
A value can be assigned to an index in all arrays.
A cell is the functional data object in MATLAB. It can contain any
data, an array of numbers, strings, structures, or cells. An array of
cells is called a cell array.
For example, one cell of a cell array contains an array of real
numbers, another an array of strings, and yet another a vector of
complex numbers.
Cell Arrays in
MATLAB
In programming terms, each element of a cell array is a pointer to
another data structure, and those data structures can be of
different types.
Cell arrays provide a great way to collect information about a
problem because all of the data can be kept together and accessed
by a single name.
Cell arrays use braces :”{ }” instead of parentheses "()" for selecting
and displaying the contents of cells. This difference is because cell
arrays contain data structures instead of data. Suppose that the
Cell Arrays in cell array a is defined as shown in the figure.
MATLAB
Each element of a cell array holds a pointer to another data
structure, and different cells in the same cell array can point to
different types of data structure.
Then the contents of element a (1, 1) is a data structure containing
a 3 x 3 array of numeric data, and a reference to a (1, 1) displays
the contents of the cell, which is the data structure.
Cell Arrays in By contrast, a reference to a {1, 1} displays the contents of the data
item contained in the cell.
MATLAB
Cell Arrays
Example
When an ordinary array is declared, MATLAB creates a memory
location for every element in the array. For example, the function
a = eye (10) creates 100 elements arranged as a 10 x 10 structure.
In this array, 90 of those elements are zero!
This matrix requires 100 elements, but only 10 of them contain
nonzero data. This is an example of a sparse array or sparse
matrix.
A sparse matrix is a large matrix in which the vast majority of the
elements are zero.
Sparse Array Sparse Attribute:
MATLAB has a particular version of the double data type that is
designed to work with sparse arrays.
In this particular version of the double data type, only the nonzero
elements of an array are allocated memory locations, and the
array is said to have the "sparse" attribute.
An array with the sparse attribute saves three values for each
nonzero element: the value of the element itself and the row and
column numbers where the element is located.
MATLAB is a programming language, as well as an interactive
computational environment. Files that include code in the
MATLAB language are called M-files.
Matlab files are called "M-files" because they must have the
filename extension ".m" at the end.
Types of M-Files:
MATLAB There are two types of M-Files:
M-Files M-File Scripts: Scripts do not accept input arguments or return
output arguments. They operate on data in the workspace.
M-File Functions: Functions can accept input arguments and
return output arguments. Internal variables are local to the
function.
We can use the MATLAB editor or any other text editor to create
our .m files.
A script file is an external file that includes a sequence of MATLAB
statements. Script files have a filename extension .m and are
known as M-files.
M-files can be scripts that execute a list of MATLAB statements, or
they can be functions that can accept arguments and can produce
one or more outputs.
Create Script using MATLAB editor
On clicking the new script icon or using the keyboard shortcut, a
M-File Scripts blank untitled file gets opened.
The blank file has a default directory to save it. We can change the
file storage location as per our requirement.
Create Script using Command Window of MATLAB
Use the edit command to create a script at the command line.
When the edit command is entered with the filename, and if the
file doesn't exist, then it prompts to create a new one. Click yes to
create the new script.
Functions are M-files that can obtain input arguments and return
output arguments. The names of the M-file and the function
should be the same.
Functions perform on variables within their own workspace, which
is also called the local workspace, separate from the workspace
you access at the MATLAB command prompt, which is known as
the base workspace.
MATLAB
Function files are like programs or subroutine in FORTRAN,
Functions operations in PASCAL, and functions in C.
A function file starts with a function definition line, which has a
well-defined record of inputs and outputs. Without this line, the
file develops into a script file.
Syntax:
function [output variables] =function_name(input variables);
where function_name must be the same as the filename (without
.m extension) in which the functions are written.
For example
function [theta] = angleTH(x, y);
File name must be angleTH.m
MATLAB
Functions function f = fact(n) Function definition line
% Compute a factorial value. H1 line
% FACT(N) returns the factorial of N, Help text
% generally indicated by N!
% put simply, FACT(N) is PROD(1:N). Comment
[m,n] = size(x);
if (~((m == 1) | (n == 1)) | (m == 1 & n == 1))
% Flow control error('Input must be a vector')
% Error message displays
end
y = sum(x) / length(x); % Calculation and assignment
Difference
between
scripts and
functions
Input to a
script file
Input to a
script file
Example
MATLAB automatically generates a display when commands are
executed. In addition to this automatic display, MATLAB has
several commands that can be used to generate displays or
outputs.
Two commands that are frequently used to generate output are:
disp and fprintf.
Output The main differences between these two commands can be
Commands summarized as follows:
Saving output
to a file
Syntax:
imread('filename')
Example:
f = imread('chestxray.jpg');
OR
Reading image f = imread('D:\myimages\chestxray.jpg');
It will show you value of pixels.
To display the image
imshow(f);
Note:- imread() will read the image from current directory in
matlab.
Image Processing Toolbox provides a comprehensive set of
reference-standard algorithms and workflow apps for image
processing, analysis, visualization, and algorithm development.
You can perform image segmentation, image enhancement, noise
reduction, geometric transformations, and image registration
using deep learning and traditional image processing techniques.
Image The toolbox supports processing of 2D, 3D, and arbitrarily large
images.
Processing Image Processing Toolbox apps let you automate common image
Toolbox processing workflows. You can interactively segment image data,
compare image registration techniques, and batch-process large
datasets. Visualization functions and apps let you explore images,
3D volumes, and videos; adjust contrast; create histograms; and
manipulate regions of interest (ROIs).
You can accelerate your algorithms by running them on multicore
processors and GPUs.
The basic data structure in MATLAB is the array, an ordered set of
real or complex elements. This object is naturally suited to the
representation of images, real-valued ordered sets of color or
intensity data.
MATLAB stores most images as two-dimensional matrices, in
which each element of the matrix corresponds to a single discrete
pixel in the displayed image.
Images in
For example, an image composed of 200 rows and 300 columns of
MATLAB different colored dots would be stored in MATLAB as a 200-by-300
matrix.
Some images, such as truecolor images, represent images using a
three-dimensional array. In truecolor images, 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 shows how to read an image into the workspace,
adjust the contrast in the image, and then write the adjusted
image to a file.
Step 1: Read and Display an Image:
Read an image into the workspace, using imread command., and
stores into array named I.
Basic Image I = imread(‘pout.tif’);
Display the image using imshow function. You can also view
Import, image in the image viewer app by imtool function.
Processing, imshow(I);
and Export
Step 2: Check How the Image Appears in the Workspace:
Check how the imread function stores image data in the
workspace, using whos command.
imread function returns the image data in the variable I, which is
291x240 element array of uint8 data.
Basic Image
Import,
Processing,
and Export Step 3: Improve Image Contrast:
View the distribution of an image pixel intensities. The image pout.tif
is a somewhat low contrast image. To see the distribution of
intensities in the image, create a histogram by calling the imhist
function.
Conclusion: Histogram indicates that the range of intensity of image
is narrow. Range does not cover the potential range of [0, 255].
Basic Image
Import,
Processing,
and Export
Image Types in
the Toolbox:
Binary images
Indexed Images: An indexed image consists of an image matrix
and a color map. A color map is an mx3 matrix of class double
containing value in the range [0, 1]. Each row of color map
specifies the red, green and blue components of a single color.
The figure illustrate an indexed image, the image matrix, and the
Image Types in color map.
the Toolbox:
Indexed
images
Grayscale Images: A grayscale image is a data matrix whose
values represent intensities of one image pixel.
The figure shows a grayscale image of class double whose pixel
values are in the range [0, 1]
Image Types in
the Toolbox:
Grayscale
Images
Truecolor Images: A truecolor image is an image in which each
pixel has a color specified by three values. Graphics file formats
store truecolor images as 24-bit images, where three color
channels are 8 bits each.
RGB images are the most common type of truecolor images. In
RGB images, the three color channels are red, green, and blue.
Image Types in
The color of each pixel is determined by the combination of the
the Toolbox: intensities stored in each color channel at the pixel's location.
Truecolor
Images
function Description
bwdist Compute the distance transform of a binary image.
bwlabel Calculate label connected components on a 2-D binary image.
bwmorph Apply morphological operations on a binary image.
edge Find edges in an intensity image.
Image imhist Calculate the histogram of an image.
Processing histeq Enhance contrast using histogram equalization.