Categories
3. Matlab Functions

Matlab Image Segmentation

Image segmentation refers to an image processing technique where an image or an object in an image is segregated, meaning that its parts are broken into pieces. Pixels are differentiated so they could be analyzed for different regions and a universal background image data. Usually, it analyses pixels on two tests of how do they connect to their neighboring objects similarly or intermittently; also Matlab differentiates pixels on their properties so they may be divided into regions for a hypothetical scenario and how the output of images being put in there would be.

As a realistic implementation, MRI uses this technique to detect non-relating pixels on body images that may be potential tumors.

How does Image Segmentation work in Matlab?

Image segmentation is the differentiation of the pixels into particular regions. The image segmentation process allows a user to divide and put apart different parts of the image and gives the freedom to use the required part. This technique helps point out abnormalities or detect a particular problem when an image generates.

There are two ways of processing the segmentation

  • Noticing the cluster of pixels that don’t belong in the pattern
  • Looking for similarities.

1. Image segmentation in MATLAB

Matlab provides the user with not a single but multiple tech gateways for the segregation of images. Matlab has been developed with in-depth research and has integrated algorithms for segmentation and image analysis.

2. Apps from Matlab for image segmentation

The first great feature of Matlab is a vibrant and efficient app built for image segmentation. This app has the pre-integration of various image processing techniques that segments your image through different methods and systems. At last, you can compare the results and choose the effect required.

3. Apps from Matlab for color thresholding

The second application applying different segmentation techniques is thresholding. Thresholding means detecting color groups or color codes in an image and separating them to create a region of particular colors. For example, you can use it in filtering images and thresholding colors from it for creating a mask or other cloud images.

Example:

The below example has demonstrated segmenting an image in the Image Segmenter app with thresholding.

Step 1: Loading the image to Image segment or App:

Go to MATLAB® toolstrip> Image Segmenter app> Image Processing and Computer Vision >Apps  >click Image Segmenter >Load> Load Image from Workspace

Matlab Image Segmentation output 1

Step 2: Using Threshold for image segmentation

Image Segmenter app toolstrip>Create Mask section>Click Threshold.

Matlab Image Segmentation output 2

Other Methods of Matlab Image Segmentation

Here are the other methods of Matlab image segmentation which are mention below:

1. Mapping and Graphing

Mapping and Graph-based image segmentation techniques are similar to what graphs do. Graphs divide the diagram or structure into its axis or directions; in the same way here, the image is divided into foreground matter and background rest. Again, you have lazy snapping available for this, or you can use an application alternative that is an easy option from Matlab.

2. Clustering

Clustering is seen in the image segmentation of injury or hit analysis. You can divide the image into clusters of particular markings. So cluster lets you separate the marked area from the rest.

3. Growing the segments on a region

Image segmentation, as we know, includes most of the region-based division of pixels of an image. It makes an object as an image and grows pixels there to take an object’s image segmented. Matlab apps also help you with it.

So these were some popular methods for image segregation and how MATLAB is an efficient platform to do so.

4. Deep Learning Technique

As the name suggests, deep learning uses a semantic type of segmentation technique that can even sort a single pixel and mark it. It is done with the help of CNN’s. This kind of image processing is used in deep sensing utilization such as maps, location generating, or satellite image transfer.

Examples of Pull right bootstrap

Here are the following examples mention below

Example #1 – Medical Image Segmentation

This use is particularly essential and uses a clustering technique of image segmentation. For example, pathologists look for tissue injuries or internal wounds via giving body tissues (H&E) separation. Where clusters of the same tissues are of the same color and inconsistencies, appear in different groups.

Example #2 – Automated Driving Vehicles

When data scientists and analysts conceptualize driverless cars or automated driving, they use semantic image segmentation techniques. It uses the method of differentiating the vehicle and other distractions or objects on the road. A particular segment helps vehicles identify particular things in real life.

Example #3 – Miscellaneous

OCR text detecting in the image, microorganisms for researchers, detecting impurities and faults in material, face detection in security surveillance and defects detection, etc.

Advantages of Image Segregation In Matlab:

  • Large Database- Matlab has a vast range of pre-installed methods and image processing techniques for different computing ways.
  • Matlab lets the user check methods and algorithms without the need to compile them again and again.
  • Matlab decreases the complications with image segmentation with the memory of tasks and diverse user interface. This interface enables the user with easy operations for any image segmentation tasks.
  • Matlab provides regular updates for performance enhancement and feature improvement.
  • Matlab is a great platform that has a vast number of users and a client-friendly community.
  • Matlab has lots of free examples and guidance for new users.
  • Matlab allows you to read and analyze several image formatting and different image segmented outputs.
  • Experienced and trained technical staff and user response team are always eager to help the user and improve the Matlab.
  • Embedded features include a unique Coder, an increasing and detailed number of image segmentation, and mathematics algorithm features that combine many elements of different programming environments.
  • Another charm over all the features is the freedom to call third-party libraries and integrate multiple techniques in their image segmentation apps.
  • Customization is a keen quality of the Matlab.
Categories
3. Matlab Functions

Matlab Images

Image Processing apps are provided by MATLAB in the form of a toolbox that helps us in automating commonly used image processing techniques and workflows by enabling interactive segmentation of image data, comparison of image registration methods, and batch processing of large datasets. Image processing in MATLAB lets us explore any image or video and make changes like adjusting the contrast, manipulating ROI (regions of interest) and create histograms to understand the definition of the image.

Here is the list of some of the most commonly used functions for processing image in MATLAB:

  • imread(): This function is used to read or load the image which we want to process
  • imshow(): This function is used to display the image that we have loaded
  • imagesc(): This function is used to display the image by utilizing the full set of colors present in the colormap. A color scale can also be used after calling this function to get a better idea of the colors present
  • imhist(): Using This function we can check how the pixel intensity of the image is distributed
  • histeq(): Using this function we can edit the contrast of our image
  • imwrite(): This function is used to insert our edited image into a file
  • iminfo(): This function is used to confirm if our edited file is loaded into a disk file

Functions for Matlab Images

Let us now understand the use of all the above functions in MATLAB. We will use an image that is stored in MATLAB’s image processing app and will execute all the above functions in steps for that image.

Step 1

In the first step, we Load or Read the image into our workspace.

Code:

imageInput = imread ('moon.tif');[‘imread’ will read the image and will store it in the array ‘imageInput’]

Step 2

In this step we will display our image in the workspace.

Code:

imshow (imageInput)[‘imshow’ will display the image as output in the workspace]

Matlab Images-1.1

As we can see in the output, the image is loaded in our workspace.

Step 3

In this step we will display our image with the colors from the colormap. We will also use a color bar to check the intensity of the colors.

Code:

imagesc (imageInput)[‘imagesc’ will display the image with a full range of colors from the colormap]

colorbar[‘colorbar’ is used to display a scale next to the image to check the intensity of the colors]

Matlab Images-1.2

As we can see in the output, the image is displayed and has a full range of colors in the colormap and we also have a color bar next to it.

Step 4

In this step we will check the intensity of pixels in our image. We will be using the figure function to display the intensity in the form of a histogram.

Code:

figure[Used to display the histogram for intensity]

imhist (imageInput)[‘imhist’ will create distribution of the pixel intensities]

Matlab Images-1.3

As we can see in the output, the range of pixel intensity for our image is very narrow, i.e the values are concentrated in a small range at the beginning.

Step 5

In this step, we will edit the contrast of our image. This is done because we found in the above step, that our image has very narrow pixel intensity.

Code:

newImage = histeq (imageInput);[‘histeq function will improve the pixel intensity or we can say that it will improve the contrast of our image]

figure
imshow (newImage)
[Displaying our new image (with improved contrast]

Output-1.4

As we can see in the output, the contrast of our image has changed drastically.

Step 6

In this step, let us call ‘imhist’ function again with ‘newImage’ as the input. This will confirm that contrast or pixel intensities of the new image created are now distributed in a better way

Code:

figure
imhist (newImage)

Output-1.5

As we can see in the histogram above, the pixel intensities of the new image created are now distributed in a better way.

Step 7

In this step, we will insert the new image into disk file.

Code:

imwrite (newImage, 'moon2.png');[Using ‘imwrite’ to save the image in disk file]

Step 8

Finally, we will confirm if our image is saved in the disk file or not using the ‘iminfo’ function. This will also give us all other details like file size, format, width, height, etc.

Code:

imfinfo ('moon2.png')[Getting the information of the saved file]

Output-1.6

As we can see in the output, the file is saved as expected by us. We also have all other information related to the image.

Categories
3. Matlab Functions

num2str in Matlab

‘num2str’ function is used to convert numeric data into character data. In this function, there is no limitation of data. Data can be in the form of a single element, array, vector, or multidimensional matrix. All types of data can be used within a function. The output of this function completely depends on the magnitude of the input data. Along with input data, we can pass precision as well as the format of output also.

Syntax:

Op = num2str ( in )
Output variable name = num2str ( input variable name )

Op = num2str ( in , 1 )
Output variable name = num2str (input variable name, precision value)

Op = num2str ( in , e )
Output variable name = num2str (input variable name, format of output )

Examples of num2str Matlab

This function converts input data independently if we are using simple function num2str. If we are using num2str function with precision then the output will show maximum digits depending on precision. Let us assume one number 3.456 if we apply num 2 str function with precision 2 then it will ignore all other digits except the first two digits that means the output will be 3.4. if precision is 3 then the output will be up to three digits 3.45. And if we are using num2str function along with format specifier then the output will change as per format given by the user.

Example 1:

In this example 1 ( a ) let us assume five different inputs in1, in2, in3, in4, and in5.all the inputs are integers 4, 7, 12, 55, and 34 respectively. The output of all inputs is op1, op2, op3, op4, and op5. In the second part, 1 ( b ) input is in the form of an array or we can say vector so the output will also be in the form of an array. And in third part 1 ( c ) input is in form of a multi-dimensional matrix with three rows and three columns so that output will also be in form of a multi-dimensional matrix with three rows and three columns.

Matlab Program of Example 1 ( a )

clc ;
clear all ;
in1 = 4
in2 = 7
in3 = 12
in4 = 55
in5 = 34
op1 = num2str ( in1 )
op2 = num2str ( in2 )
op3 = num2str ( in3 )
op4 = num2str ( in4 )
op5 = num2str ( in5 )

Output:

num2str in Matlab-1.1

Matlab Program of Example 1 ( b) 

clc ;
clear all ;
in1 = [ 65 54 43 55 43 ] op1 = num2str ( in1)

Output:

num2str in Matlab-1.2

Matlab Program of Example 1 ( c )

clc ;
clear all ;
in1 = [ 65 55 43 ; 8 76 0 ; 65 23 22 ] op1 = num2str (in1)

Output:

num2str in Matlab-1.3

Example 2

In this example, num2str function is applied along with precision. In first part, precision is 2 and in second part precision is 4 .input data is a multi-dimensional matrix with three rows and three columns for both the examples example 2(a) and example 2(b). We can observe the difference in both parts 2 (a) and 2 (b) in the form of digits. Example 2(a) will show output till 2 digits and example 2(b) will show up to four digits.

Matlab Program of Example 2 ( a )

clc ;
clear all ;
in1 = [ 1.223  2.44  4.3334 ; 3.244 5.255 7.5363 ; 6.2425 7.24 5.647 ] op1 = num2str ( in1 , 2 )

Output:

Output-2.1

Matlab Program of Example 2 ( b)

clc ;
clear all ;
in1 = [ 1.223 2.44 4.3334 ;    3.244 5.255 7.5363 ; 6.2425 7.24 5.647 ] op1 = num2str ( in1, 4 )

Output:

Output-2.2

Example 3

In this example let us assume input in the form of a multi-dimensional matrix with three rows ad four columns. Num2str function is applied along with the format specifier. This format specifier converts integer data in character or string as per format. In this example, we have pass one format specifier 9.5 e. This specifier is applicable to all elements of input irrespective of the type of input data.

Matlab Program of Example 3

clc ;
clear all ;
in1 = [ 54 54 32 43 ; 43 56 66 0 ; 43 23 22 1 ] op1 = num2str ( in1 ,' %9.5e\n ' )

Output:

Output-3.1
Categories
3. Matlab Functions

Feval in Matlab

MATLAB is a programming environment that is interactive and is used in scientific computing. It is extensively used in a lot of technical fields where problem-solving, data analysis, algorithm development, and experimentation is required. Software which are discipline-specific are extensively written using MATLAB.
In this article, we will study how to use ‘feval’ function in MATLAB.

Before we start learning how ‘feval’ function works in MATLAB, let us understand why we need it.

Feval Function:

Feval function is used to evaluate the function output of a function by using the arguments passed inside a single parenthesis input. It accepts the function name passed as a “string”, as its first argument. Feval function is used to make the code easy to understand or read, as we use parentheses in it for both function invocation and indexing.

Please keep in mind that MATLAB suggests the use of a ‘function handle’ for the purpose of reference invocation. Function handles have the advantage of reliability, additional performance, and offers source file controlling.

Let us now understand the syntax of ‘Feval function’ in MATLAB:

Syntax:

[a1, a2, ..., aN] = feval (function, inp1, inp2, ..., inp M)

Description:

1. feval takes a function as its first argument, which is passed as a string (in quotes)
2. The name of the function is usually defined by M-file
3. feval (function, inp1, inp2, …, inp M) will evaluate the value of ‘function’ at the input arguments.
4. Function parameter here must be name of a function, we cannot use path information.

Examples of feval Matlab

Let us now understand how the code for ‘feval function’ looks like in MATLAB, with the help of various examples.

Example 1:

In this example, we will find the average of elements of an array using ‘feval function’ We will need to follow the following 2 steps:

1. Create an array whose average we need

2. Pass the function ‘mean’ as a string inside the function ‘feval’

Code:

A = [1 4 6 7 0 2][Defining the input array ‘A’] [Mathematically, the mean of A must be 3.3333]

feval (‘mean’, A)[Passing the mean function as 1st argument and input array ‘A’ as 2nd argument]

Input:

A = [1 4 6 7 0 2] feval ('mean', A)

Output:

feval Matlab 1

As we can see, by passing ‘mean’ as input argument to our ‘feval function’, we are able to get the mean of our input array.

Example 2

In this example, we will find the standard deviation of elements of an array using ‘feval function’ We will need to follow the following 2 steps:

1. Create an array whose standard deviation we need

2. Pass the function ‘std’ as a string inside the function ‘feval’

Code:

A = [2 4 9 15 0 2][Defining the input array ‘A’] [Mathematically, the standard deviation of A must be 5.6451]

feval (‘std’, A)[Passing the std function as 1st argument and input array ‘A’ as 2nd argument]

Input:

A = [2 4 9 15 0 2] feval ('std', A)

Output:

feval Matlab 2

As we can see, by passing ‘std’ as input argument to our ‘feval function’, we are able to get the standard deviation of our input array.

Example 3

In this example, we will find the value of sine function at a particular point. We will need to follow the following 2 steps:

1. Pass the ‘sin’ as a string inside the function ‘feval’

2. Pass the point, at which we need to get the value, as 2nd argument

Code:

A = -pi/2[Defining the point at which we need value of sine function] [Mathematically, the value of sin is -1 at -pi/2]

feval (‘sin’, A)[Passing the sin function as 1st argument and the point -pi/2 as 2nd argument]

Input:

A = -pi/2
feval ('sin', A)

Output:

feval Matlab 3

As we can see, by passing ‘sin’ as input argument to our ‘feval function’, we are able to get its value at -pi/2.

Example 4:

In this example, we will combine two input strings using ‘strcat’ function. We will need to follow the following 2 steps:

1. Pass the two input strings inside the function ‘feval’

2. Pass the function ‘strcat’ to concatenate the 2 strings

Code:

a = feval ('strcat', 'learn', ' feval')[‘strcat’ is passed as 1st argument] [Passing the strings ‘learn’ and ‘feval’ as 2nd and 3rd argument respectively]

Input:

a = feval ('strcat', 'learn', ' feval')

Output:

Example 4

As we can see, by passing ‘strcat’ as input argument to our ‘feval function’, we are able to concatenate the 2 input strings passed as 2nd and 3rd arguments.

Categories
3. Matlab Functions

Matlab eye

Matlab provides different types of functions to the user, the eye is one of the functions provided by Matlab. Basically, Matlab eye () is used to identify the n by n matrix whose main diagonal is ones and zeros, otherwise, Matlab eye () function returns the n by m matrix whose main diagonal is ones and zeros. If we specify the size with Matlab eye () function then I return the array diagonal with ones and zeros. Normally Matlab eye () function is used to identify the matrix as per the user requirement for different purposes.

Syntax

There are multiple syntaxes available for Matlab eye () as follows.

Variable name = eye
Variable name = eye (n by n matrix)
Variable name = eye (n by m matrix)
Variable name = eye (array size)

Explanation

In the first syntax, we use different parameters such as variable name means an actual variable name that depends on the user and after that, we use the eye () function. In this syntax eye () is used to return scalar 1.

In the second we pass the size of a matrix with eye () function as shown in the above syntax. That means it is used to identify the n by n matrix whose main diagonal is ones and zero.

In the third syntax we define n by m size of matrix it is also used to return whose main diagonal is ones and zeros elsewhere.

In the fourth syntax, we define the array size as shown in the above syntax, which means it returns the ones on the main diagonal and zeros elsewhere.

How does the eye work in Matlab?

Now let’s see how the eye () function works in Matlab as follows. Now let’s see the different input arguments that are required for the eye () function as follows.

Dimension Size of the first variable (n):

Normally dimension size of the first variable is always an integer and it has the following properties as follows.

Here we consider n and I variables for an explanation.

  1. If the value of n is only an integer input argument then matrix (I) is a square that we can consider as n – by- n matrix.
  2. If the value of n is zero then we can consider the matrix as empty.
  3. If the value of n is negative then we can consider it as 0 or we can treat it as a 0.

It uses different data types such as double, single, int8, int16…Up to int64.

Dimension Size of the second variable (m):

Normally dimension size of the second variable is always an integer and it has the following properties as follows.

  1. If the value of m is 0 then the matrix is 0.
  2. If the value of m is negative then we consider it as 0 or we can treat it as a 0.

It also uses the same data types that mean double, single, int8, int16…Up to int64.

Size of the array (sa):

It is used to specify the row vector that does not have more than two integer values and it also has the following properties as follows.

  1. If the size is 0 then we can consider the matrix as empty.
  2. If the size is negative then we can consider it as 0.

It also uses the same data types such as double, single, int8, int16…Up to int64.

Examples

Now let’s see different examples of Matlab eye () function for better understanding as follows.

Now let’s see a very simple example of eye () function

A = eye(5)

Explanation

In the above example, we try to create an n – by – n matrix by using the Matlab eye () function; here the value of n is 5 so we created a 5 by 5 matrix and A is the variable name that we assign for the matrix. Notice here all diagonals are ones and other elements are zero. The final output of the above statement we illustrated by using the following screenshot as follows.

Matlab eye output 1

Similarly, we can create a square matrix by using the eye () function as follows.

A = eye(4)

Explanation

By using the above statement we try to create the 4 by 4 square identity matrix. In which all diagonals are ones and other elements are zeros. The final output of the above statement we illustrated by using the following screenshot as follows.

Matlab eye output 2

Now let’s see another example of eye () function as follows.

A = eye(3,4)

Explanation

By using the above statement we try to implement the rectangular matrix. Here the size of the matrix is 3 by 4 as shown in the above statement. The final output of the above statement we illustrated by using the following screenshot as follows.

Matlab eye output 3

Now let’s see how we can create the identity vector as follows.

A = [5,1] B = eye(A)

Explanation

By using the above statement we try to create the 5 by 1 identity vector. Here first we specify the size of the vector and after that, we call that vector by using the eye () function as shown. The final output of the above statement we illustrated by using the following screenshot as follows.

output 4

Now let’s see the example of non-default data type as follows.

A = eye (4, "uint16")

Explanation

In the above example, we use uint16 data type as shown, here we created a 4 by 4 matrix. The final output of the above statement we illustrated by using the following screenshot as follows.

output 5

Now let’s see some complex examples as follows.

A = [2+3i, 4i] B =eye(3,'like',A)

Explanation

By using the above example we try to implement the complex example. In this example, we use a complex value like an array, or we can say that it is not a real value. The final output of the above statement we illustrated by using the following screenshot as follows.

output 6

So in this, we can implement the Matlab eye () function as per our requirement.

Categories
3. Matlab Functions

Matlab color codes

Matlab provides the color code functionality to the user. Basically, Matlab is a very good visualization and by using color codes we can draw a variety of graphs. In which users can be able to plot any color as per their requirement. Matlab provides different color combinations such as blue, green, red, cyan, and magenta, yellow, black and white, etc. So we can use any color combination to plot the graph or any other uses such as 3D works. By using color codes we can use any color, the color contains the hexadecimal value or we can say that RGB values. Another way to access the color code is that we can use short names and long names to access the color codes.

Syntax

A = expression 1;
B = expression 1:
Plot (A, B, ‘Color’, ‘Color code’)

Explanation

In the above syntax, we use two different expressions, with the help of these two expressions we plot the graph, and that expression we specify by using the variable name that A and B as shown in the above syntax. After that we plot the function to draw the graph with the desired value that we mentioned in the expression, here we just call the variable A and B with color code. The color code parameter is used to specify the color that we want to use to draw the graph.

How do color codes work in Matlab?

Now let’s see how color code works in Matlab as follows.

Basically, there are different ways to use color code as follows.

First is that RGB value:

The first way we use color code in Matlab, here we can use RGB value for color code and it contains the three different elements and that specify the basic color combination such as red, green, and blue, and range of this element is that [0 1].

For example:

Suppose we need to use black and red to plot the graph at that time we can use the following RGB value for that color as follows.[0 0 0] for black and [1 0 0] for red as per our requirement we can use any color code combination.

Now let’s see the second way is that short name:

This is a second way to import the color in Matlab, here instead of RGB value we can use short naming of color.

For example:

Suppose we need to import the yellow and cyan color in Matlab at that time we can use the following short names of color as follows.

for yellow and c for cyan.

Now let’s see the third way is that long name:

In this method, we can use the full name of color instead of RGB and short name as per user requirement that we call long name.

For example:

Suppose we need to plot the graph with magenta and green at that time we can use the same name of the color that magenta and green.

There is another way to use color code is that hexadecimal code combination.

Examples

Now let’s see the different examples of color code in Matlab for better understanding as follows.

x = linspace(-3*pi,3*pi);
y = sin(x);
hex = '#FF00011';
colorcode = sscanf(hex(2:end),'%2x%2x%2x',[1 3])/255;
figure
plot(x, y, 'Color', colorcode)

Explanation

In the above example we have two expressions for x-axis and y-axis as shown, after that, we specify the hexadecimal code that we want to use and that code we store into the hex variable. Notice here we use hexadecimal color code but we need to convert it into the RCG value as shown in the above example. The remaining part of this example is simple which means we plot the graph with color parameters. The find output of the above example we illustrated by using the following screenshot as follows.

Matlab color codes output 1

Now let’s see how we can use the short names in Matlab as follows.

plot([1 2 3],'-b')
hold on
plot([3 2 1],'--r')
hold off

Explanation

This is a very simple example of plotting the graph, here we plot a graph with two different lines such as dotted and solid with the different color combinations as shown in the above example. The find output of the above example we illustrated by using the following screenshot as follows.

Matlab color codes output 2

Now let’s see another example of color code as follows.

A=-200:1.2:200;
B=A.^4-A.^1;
plot(A,B,'b')

Explanation

This is another example of a short name color code; here suppose we need to plot the graph with blue color at that time we can use a b character instead of the blue word as shown in the above example. The find output of the above example we illustrated by using the following screenshot as follows.

Matlab color codes output 3

Now let’s see how we can draw lines in triangle format as follows.

A=-200:1.2:200;
B=A.^4-A.^1;
plot(A,B,'vm')

Explanation

Here we consider the same example, in this example we just add the v with the color code as shown and the direction of a triangle is downward. The find output of the above example we illustrated by using the following screenshot as follows.

output 4

Similarly, we can draw the line by using the triangle with upward as follows.

A=-200:1.2:200;
B=A.^4-A.^1;
plot(A,B,'^m')

Explanation

In this example, we just change the color code ^m instead of vm as shown in the above example. The find output of the above example we illustrated by using the following screenshot as follows.

output 5

Now let’s see how we can use star patterns in line with the color code as follows.

A=-200:1.2:200;
B=A.^4-A.^1;
plot(A,B,'*c')

Explanation

By using the above example we try to plot the line with star pattern here we just add the * symbol with color code here we use cyan color code as shown in the above example. The find output of the above example we illustrated by using the following screenshot as follows.

output 6

Similarly, we can use different shapes to plot the graph such as circle, plus, triangle, square and diamond, etc.

Categories
3. Matlab Functions

Matlab xcorr

MATLAB’s xcorr method can be used to compute the cross-correlation of 2 time-sequences which are discrete in nature. The main aim of computing cross-correlation is to enable the use of a part of any incoming signal or beam to examine the transient evolution that is being produced by the second part. It can also be used to get the additional information of the incoming signal or beam itself which is otherwise tricky to measure.

Syntax:

  1. C = xcorr (a, b) is used to return the cross-correlation between two time sequences (discrete in nature).
  2. The method ‘xcorr’ will compute the similarity between vector ‘a’ & lagged copies of vector ‘b’
  3. C = xcorr (___, maximumlag) is used to limit the maximum lag as per the requirement

Let us now understand how to compute the cross-correlation in MATLAB using ‘xcorr’ method:

Examples of Matlab xcorr

Let us discuss examples of Matlab xcorr.

Example 1:

In this example, we will use the xcorr method to compute the cross-correlation between 2 vectors. The steps to be followed for this example are:

  1. Create a vector ‘a’
  2. Create another vector ‘b’, with a shift of required units from ‘a’
  3. Pass the above 2 vectors as arguments to the xcorr method
  4. Use the stem method to plot the output

Code:

x = 0 : 20

[Initializing the size of the vector]

a = 0.108.^x;

[Initializing the vector ‘a’]

b = circshift(a, 10);

[Initializing the vector ‘b’. Here we have used ‘circshift’ method to get a vector which is shifted by 10 elements from ‘a’]

[c, lag] = xcorr(a, b);

[Using the xcorr method to get the cross correlation]

stem(lag, c)

[Using stem method to plot the output]

This is how our input and output will look like in Matlab command window:

Input:

Matlab xcorr 1

Output:

Matlab xcorr 2

As we can see in the OUTPUT, largest spike comes at -10; i.e. when the elements of a & b match exactly, which is the same as expected by us.

Example 2:

Let us take another example where we will use xcorr method to compute the cross-correlation between 2 vectors. The steps to be followed for this example are:

  1. Create a vector ‘a’
  2. Create another vector ‘b’, with a shift of required units from ‘a’
  3. Pass the above 2 vectors as arguments to the xcorr method
  4. Use the stem method to plot the output

Code:

x = 0 : 40

[Initializing the size of the vector]

a = 0.48.^x;

[Initializing the vector ‘a’]

b = circshift(a, 8);

[Initializing the vector ‘b’. Here we have used ‘circshift’ method to get a vector which is shifted by 8 elements from ‘a’]

[c, lag] = xcorr(a, b);

[Using the xcorr method to get the cross correlation]

stem(lag, c)

[Using stem method to plot the output]

This is how our input and output will look like in Matlab command window:

Input:

Matlab xcorr 3

Output:

Matlab xcorr 4

As we can see in the OUTPUT, largest spike comes at -8; i.e. when the elements of a & b match exactly, which is the same as expected by us.

In the above 2 examples there was no limit on the lag. Next, we will learn how to define a lag in the xcorr method

Example 3:

In this example, we will use xcorr method to compute the cross-correlation between 2 vectors and will limit the maximum lag. The steps to be followed for this example are:

  1. Create a vector ‘a’
  2. Create another vector ‘b’, with a shift of required units from ‘a’
  3. Pass the above 2 vectors as arguments to the xcorr method
  4. In addition to the above 2 arguments, pass a 3rd argument which will specify the maximum lag
  5. Use the stem method to plot the output

Code:

x = 0 : 50

[Initializing the size of the vector]

a = 0.90.^x;

[Initializing the vector ‘a’]

b = circshift(a, 5);

[Initializing the vector ‘b’. Here we have used ‘circshift’ method to get a vector which is shifted by 5 elements from ‘a’]

[c, lag] = xcorr(a, b, 15);

[Using the xcorr method to get the cross correlation. Please note that, we have passed a 3rd argument ‘15’, which represents the maximum lag that we need]

stem(lag, c)

[Using stem method to plot the output]

This is how our input and output will look like in Matlab command window:

Input:

example 3

Output:

example 3-1

As we can see in the output, the signal is restricted with a maximum lag of 15 as expected by us.

Example 4:

Let us take another example where we will use xcorr method to compute the cross-correlation between 2 vectors and will limit the maximum lag. The steps to be followed for this example are:

  1. Create a vector ‘a’
  2. Create another vector ‘b’, with a shift of required units from ‘a’
  3. Pass the above 2 vectors as arguments to the xcorr method
  4. Pass a 3rd argument which will specify the maximum lag
  5. Use the stem method to plot the output

Code:

x = 0 : 100

[Initializing the size of the vector]

a = 0.200.^x;

[Initializing the vector ‘a’]

b = circshift(a, 10);

[Initializing the vector ‘b’. Here we have used ‘circshift’ method to get a vector which is shifted by 10 elements from ‘a’]

[c, lag] = xcorr(a, b, 20);

[Using the xcorr method to get the cross correlation. Please note that, we have passed a 3rd argument ‘20’, which represents the maximum lag that we need]

stem(lag, c)

[Using stem method to plot the output]

This is how our input and output will look like in Matlab command window:

Input:

example 4

Output:

example 4-1

As we can see in the output, the signal is restricted with a maximum lag of 20 as expected by us

Categories
3. Matlab Functions

Matlab min

‘Min’ is function used in Matlab to find minimum or smallest value from database. This function can be applied on any type of dataset like integers, characters, floating numbers, etc. Along with type of dataset it can be applied on any dimensions of data such as arrays, vectors, two dimensional elements, three dimensional elements, etc. If values are missing in dataset then most of the times ‘NaN’ represents null values, there are two ways to apply min function on this type of datasets. First function is ‘omitnan’, which ignores Nan values and second function is ‘includenan’, which is used to include Nan values in dataset.

Syntax:

  • min ( Input variable name )

min ( Input )

  • min ( input variable name , [ ] , dimensions )

min ( Input , [ ] , 2 )

  • min ( input variable name , [ ] , ‘ includenan ’ )

min ( Input , [ ] , ‘ includenan ’ )

  • min ( input variable name , [ ] , ’ omitnan ’ )

min ( Input , [ ] , ‘ omitnan ’ )

How min function work in Matlab?

‘Min’ function gives smallest value from given input as output. It is simple process to find smallest value from integers and floating numbers, but it is difficult and complex to calculate minimum value from characters and strings. if we apply min function on characters or strings then it works on ascii values it calculates ascii values first and then find smallest number from ascii numbers.

Examples:

Let us discuss examples of Matlab Min.

Example 1:

First let us consider one simple array or vector [ 20, 41, 30, 23,12, 6, 10, 45, 34 ] , which is declared as Input. These are simple integers so output after applying min function is 6.

Matlab Code:

clc ;
clear all ;
Input = [ 20, 41, 30, 23, 12, 6, 10, 45, 34 ] disp ( ' Minimum Element ' ) ;
min ( Input)

Output:

Matlab min 1

Example 2:

Let us consider one example with character elements as input [ ‘ A ‘ , ‘ B ‘ , ‘ D ‘ , ‘ E ‘ ], which is declared as Input. In character and string database min function will find out ascii values first and then it will calculate smallest value .in this example ASCII values of A, B, D, E are 65, 66, 68, 69 respectively. Therefore smallest value is 65.

Matlab Code:

clc ;
clear all ;
Input = [ ' A ' , ' B ' , ' D ' , ' E ' ] disp ( ' Minimum Element ' );
min ( Input )

Output:

Matlab min 2

Example 3:

Let us consider one matrix as input with three rows and three columns [ 34, 32, 67 ; 34, 21, 20 ; 45, 78, 10 ] ,which is declared as Input. If input is multidimensional then min function will work on each column individually. Therefore output of this example is 34, 21 and 10 which is illustrated in example 3 ( a ). If we want output in a different way then we can give dimensions to min function. In same example let us apply dimension as 1 then output will be 34,21 and 10 that means if dimension is one then it will work on each column individually which is illustrated in example 3 ( b ). And by considering same input if we apply dimension as 2 then it will work on each row and it will give a result on each row so output will be 32, 20, and 10, which is illustrated in example 3( c ).

Matlab Code (a)

clc ;
clear all ;
Input = [ 34, 32, 67 ; 34 , 21, 20 ; 45, 78, 10 ] disp ( ' Minimum Element ' ) ;
min ( Input )

Output:

Matlab min 3

Matlab Code ( b)

clc ;
clear all ;
Input = [ 34, 32, 67 ; 34, 21, 20 ; 45, 78,10 ] disp ( ' Minimum Element ' ) ;
min ( Input,[ ] ,1 )

Output:

Matlab min 4

Matlab Code ( c )

clc ;
clear all ;
Input = [ 34, 32, 67 ; 34, 21, 20 ; 45, 78, 10 ] disp ( ' Minimum Element ' ) ;
min ( Input,[ ] ,2 )

Output:

Matlab min 5

Example 4

In this example, we will consider one value in database which is NaN. Nan represents null values in any type of database. If there are NaN values in database and we apply min function without any instruction then automatically it will ignore the NaN value, which is illustrated in example 4(a).there are two functions in min function. One is omitnan and second is includenan. ‘omitnan’ will ignore NaN values and ‘Includenan’ will consider NaN values.

Matlab code 4 (a)

clc ;
clear all ;
Input = [ 4.5 , 6.5, 6.0, 3.4, 3.2, 1.4, 1.9, 1.2, 4.9, NaN ] disp ( ' Minimum Element ' ) ;
min ( Input )

Output:

example 4

Matlab code 4(b) –

clc ;
clear all ;
Input = [ 4.5, 6.5, 6.0, 3.4, 3.2, 1.4, 1.9, 1.2, 4.9, NaN ] disp ( ' Minimum Element ' ) ;
min ( Input , [ ] , ' includenan ' )

Output:

example 4-3

Matlab Code 4( c )

clc ;
clear all ;
Input = [ 4.5, 6.5, 6.0, 3 .4, 3.2, 1.4, 1.9, 1.2, 4.9, NaN ] disp('Minimum Element');
min ( Input, [ ], 'omitnan' )

Output:

example 4-2
Categories
3. Matlab Functions

Matlab pcolor()

In MATLAB, pcolor() is the plotting function which is designed to represent the input matrix data in the form of an array of colored cells creating a pseudo color plot. The colored cell is termed as face. The plot gets created as x-y plane flat surface with x and y co-ordinates as vertices(corners) of faces. The limits for x and y co-ordinates are decided by the size of the input matrix.

Syntax:

There are different syntaxes that can be used to implement pcolor() method based on the input arguments given to it. Such as:

Where C is the input matrix data

pcolor(C)

Where C is the input matrix data

pcolor(X,Y,C)

X– x-coordinates of the vertices

Y- y-coordinates of the vertices

ax defines the axes targeted for the plot

pcolor(ax,___)

To store the pseudo color plot as surface object

s=pcolor(___)

Attributes of Matlab pcolor()

Here is the table of Attributes:

AttributeDescription
CInput matrix data
X,Ycoordinates of the vertices
Axaxes targeted for the plot

Examples to Implement Matlab pcolor()

Here are the examples mentioned:

Example 1:

create pseudo color plot for input matric Cmat.

Code:

Cmat=z=[567;111213];
pcolor(Cmat);

Output:

Matlab pcolor()1

Explanation: The input matrix is of size 2X3 and the vertices of the plot is decided 2X3 as default data. The pseudo color plot also can be created in the reverse direction using axis function.

Example 2:

Generate Hadamard square orthogonal matrix and create pseudo color plot for same,with the origin set in the upper left corner.

Code:

CMat = hadamard(40);
pcolor(CMat)
axis ij
axis square

Output:

Matlab pcolor()2

Explanation: The resultant graph is a 40X40 two-color map, represented in the reverse direction.

Example 3:

Create pseudo color plot for the input matrix data Cmat within the defined x and y coordinates given by matrix inputs X and Y.

Code:

Xcod=[1 2 4; 1 2 5; 1 2 6];
Ycod = Xcod';
Cmat = [2 4 3; 2 3 5; 6 5 6];
pcolor(Xcod,Ycod,Cmat)

Output:

Matlab pcolor()3

Explanation: The resultant plot has the vertices as per the values given by X and Y matrices and data from Cmat is plotted within the limits. The data from the input matrix are represented by different color code in the plot.

Example 4:

MATLAB supports tilling of plots using the functions like nexttile() and tiledlayout(). The below code is wriiten to create 1X2 chart layout and creating two different pseudo color plot for two different set of inputs and functions in each cell of the layout.

Code:

tiledlayout(1,2)
Lx = nexttile;
LCmat = rand(60,15);
pcolor(Lx,LCmat)
Rx = nexttile;
colorscale = [1:20; 20:-1:1];
RCmat = repmat(colorscale,10,1);
pcolor(Rx,RCmat)

Output:

Matlab pcolor()4

Explantion: The resultant plots are arranged in single layout consisting of two tiles generated using the function nexttile().

Pcolor() with Surface Object

When pcolor() method is assigned to a variable, it returns a surface object. This return value can be used to customize the properties of the plot after its creation.

Example 1:

The below code is developed create a pseudo color plot for input matrix and modify the edge color and line width after the plot is generated.

Code:

Cmat = [1 2 3; 4 5 6; 7 8 9];
s = pcolor(Cmat);
s.EdgeColor = [0.9 0.3 0.7];
s.LineWidth = 5;

Output:

Matlab pcolor()5

Explanation: The resultant pseudo color plot is assigned to variable ‘s’. The edge color and the line width of the plot is modified using ‘s’ value as shown in the output plot.

Example 2:

The below code snippet is designed to create the pseudo color plot and modify the face color of the cells using interpolated coloring using surface object properties.

Code:

Cmat = [15 3 9 17 22; 31 12 24 28 14; 16 14 23 24 25];
s = pcolor(Cmat);
s.FaceColor = 'interp';

Output:

Matlab pcolor()6

Explanation: The resultant pseudo color plot is assigned to surface object ‘s’. The color representation of the faces are modified due to modification applied to the surface object property ‘facecolor’ for the surface object ‘s’.

Semi Logarithm Plotting using pcolor()

The MATLAB plotting function pcolor() can also be used to create semi logarithmic pseudo color plot.

Example 1:

The below MATLAB code is designed to create semi logarithmic pseudo color plot and to alter the appearance using surface object properties from its return value.

Code:

[X,Y] = meshgrid(1:20);
YL = log(Y);
colorscale = [1:20; 20: -1:1];
Cmat = repmat(colorscale,10,1);
s = pcolor(X,YL,Cmat);

Output:

surface object

Explanation: The resultant output is surface plot where y-coordinate input is the logarithmic function of x-coordinate inputs. The pseudo color semi logarithmic plot generated from the pcolor() method can be stored as surface object and its properties can be altered as shown in the below example:

Example 2:

Code:

[X,Y] = meshgrid(1:20);
YL = log(Y);
colorscale = [1:20; 20:-1:1];
Cmat = repmat(colorscale,10,1);
s = pcolor(X,YL,Cmat);
logvals = YL(2:2:20,1)';
set(gca,'YTick',logvals);

Output:

alter the y-tick values

Explanation: The plot from the above code is generated with modified y-tick values by altering the properties of the surface object ‘s’.

Parametric Plotting using pcolor()

Parametric functions are also supported by pcolor() method.

Example 1:

The below MATLAB code is designed to generate pseudo color plot from the x-y co oridinates generated from parametric equations.

Code:

[Xcd,Ycd] = meshgrid(-3:6/17:3);
fX = 2*Xcd.*Ycd;
fY = Xcd.^2 + Ycd.^2;
colorscale = [1:18; 18:-1:1];
Cmat = repmat(colorscale,9,1);
pcolor(fX,fY,Cmat);

Output:
parametric equations

Explanation: The resultant plot represents the input matrix data, generated from repmat() function within the x-y coordinate values that are defined by two parametric equations.

Categories
3. Matlab Functions

Matlab fill()

In Matlab, fill() function is responsible for creating colored filled polygons from the data indicated by X and Y with vertex color acknowledged by the Colorspec that includes various color specifications. Here, Colorspec is not a type of function or command but gives us three ways to identify color for Matlab graphics to create filled areas or other related functions. It includes types such as RBG triplet, Short name, and Long name. Thus, Fill() in Matlab is used to plot filled polygons where the type of color shading is dependent on the argument list in a matrix and the vertices are recorded along with this data specified by X and Y.

Syntax:

Following is the syntax of fill () function in Matlab:

Fill (X, Y, C)              // It produces filled polygons from the data stated by X and Y with color C.
Fill (X, Y, ColorSpec)          // It is used to fill 2D polygons identified by X and Y with the color specified
Fill (X1, Y1, C1, X2, ….., Xn, Yn, Cn)       // It is used for multiple 2D filled areas in Matlab fill ()
Fill (…, ‘property_name’, property_value)
Fill(ax,..)
h = fill (…..)

Working of Matlab fill()

  • In Matlab, the fill (X, Y, C) function creates filled polygons form the statistics in X and Y along with the vertex color that is identified by C. Here, C is recognized as a matrix that helps as an index in the color map. Suppose, if we consider C as a row vector, then length (C) should be equal to size (X, 2) and size (Y, 2). Also, when we consider C as a column vector then, length(c) should be equal to size (X, 1) and size (Y, 1).
  • If it is required then fill () function in Matlab can close the polygon by connecting the last vertex with the first one. We can add numeric values or date-time, categorical or durational values in X and Y.

Now, you can use the fill function to create any shaded area as follows:

  • Fill (X, Y, ColorSpec) can fill two-dimensional polygons indicated by X and Y with a color identifier that is ColorSpec.
  • To define multiple two dimensional filled areas, we can use the following structure of fill () function in X and Y with color vertex C: fill (x1, Y1, C1, X2, Y2, C2, ………, Xn, Yn, Cn) where n is number of terms used as necessary for the matrix or create a fill polygon.
  • Also, the fill () function helps to specify any property name and respective values for a particular patch graphics item or object by the following syntax:

Fill (…, ‘property_name’, property_value)

  • The fill (ax, …) produces the polygons in the axes stated by ax in place of in the current axes that is gca. In the older syntaxes, the ax option can further precede any of the input argument combinations.
  • We need to know that in Matlab, h = fill (…) allows providing a vector of patch objects.

Examples of Matlab fill()

Given below are the examples of Matlab fill():

Example 1

  • To create an octagon filled with red color in Matlab using fill () function.

Firstly, declare the data and objects. Then using the fill function generating the filled area of the octagon as follows:

Code:

a = (1 / 16:1 / 8:1) ‘* 2 * pi;
x = cos (a);
y = sin(a);
fill (x, y, ‘r’)
axis square

Output:

matlab fill() 1

Example 2

Polygon of like flower design with the below code.

Code:

r = linspace (0, 2*pi, 200);
t = sqrt (abs(2*sin(5*r)));
x = t.*(cos(r));
y = t.*(sin(r));
fill (x, y, ‘k’)
axis (‘square’)

Output:

matlab fill() 2

Some Guidelines to keep in Mind

  • Suppose if X and Y are numeric data in a matrix, and another one is a column vector with an equal number of elements as rows in the matrix, then you need to fill in the duplicates of the column vector argument so that it produces a matrix of the required size.
  • Here the fill function makes a vertex from matching elements in X and Y thus, creating a polygon from the data in every column.
  • Also, if NaN values exist in X or Y, then the polygon is not filled by the fill () function.
  • Here, when you give color using ColorSpec, then the fill () function produces a flat-shaded type of polygons by stating the patch object’s property ‘FaceColor’ to the equivalent RGB triplet.
  • But, if you agree to use color by C, then the fill function balances the elements of C with the values identified by the axes property i.e. CLim after this the colormap is indexed by C.
  • The fill function produces flat-shaded polygons if C is a row vector where the color of the polygon is determined by each element which is defined by the respective column of matrices X and Y. The property of each patch object ‘FaceColor’ is fixed to ‘flat’. The CData property value is defined by each row element for the nth patch object, where n represents the corresponding column in X and Y.
  • Suppose if C is stated to be a column vector or a matrix, the fill produces polygons with interpolation colors using linear interpolation of the vertex colors. Here the FaceColor property of patch graphics object is set to ‘interp’ CData property value is defined by the elements present in one column for the respective object.
  • To create a desired sized matrix, where C is a column vector then the fill function repeats the column vector.