Categories
1. Basics of Matlab

Matlab Smooth

‘smooth’ function is used for getting smooth’s the response of input arguments using methods such as moving average, Savitzky-Golay filter and ‘lowess’ models or by fitting a smoothing spline.‘Smooth’ function gives the different result as compared to the filter function because smooth function ishandling at the endpoint. In matlab smooth functionwork by using two statements one is ‘smooth’ and another is ‘smoothdata’.The ‘smooth’ statement isuse for smooth response data.The ‘smoothdata’ statement is used forsmooth noisy data.‘smoothdata’ statement gives options like moving median and Gaussian methods.yy = smooth( y ) is used for smooths the response data in y variable

Syntax of Matlab Smooth

Syntax related to smooth response data:

  • yy = smooth(y)
  • yy = smooth(y,span)
  • yy = smooth(y,method)
  • yy = smooth(y,span,method)
  • yy = smooth(y,’sgolay’,degree)
  • yy = smooth(y,span,’sgolay’,degree)
  • yy = smooth(x,y,___)

Syntax related to smooth noisy data

  • B = smoothdata(A)
  • B = smoothdata(A,dim)
  • B = smoothdata(___,method)
  • B = smoothdata(___,method,window)
  • B = smoothdata(___,nanflag)
  • B = smoothdata(___,Name,Value)
  • [B,window] = smoothdata(___)

How does Smooth works in Matlab?

In matlab smooth ‘smooth’ statement is use for smooth response data. The ‘smoothdata’ statement is used for smooth noisy data.

The steps for smooth response data:

  • Step 1: First input argument is take in the variables.
  • Step 2: Then we use the “smooth” statement.
  • Step 3: Then we use “subplot” and “plot” to plot the smooth response data signal.

The steps for smooth noisy data:

  • Step 1: First input singnal is take in the variables which containing noise.
  • Step 2: Then we use “smoothdata” to smooth noisy data.
  • Step 3: Then we use “subplot” and “plot” to plot the smooth response data signal

Examples of Matlab Smooth

Following are the examples are given below:

Example 1:

Let us see one example of matlab smooth. A basically smooth function used for decreasing noise contain in the signals. In this example, we discuss about how smooth function is used for reducing the noise. In this example, we take Y in the range of 0 to 30 with 0.1 differences. Then a continuous and distorted signal y generated with the help of y signal. Now we use smooth statement to reducing the noise within signal y = sin(Y) + 0.5*(rand(size(Y))-0.5) .To reducing the noise within signal loess and rloess methods are used. The processed signal is stored at yy1 and yy2 respectively. Now subplot and plot function are used to plot the data. A subplot(2,1,1) and plot(Y,y,’b.’,Y,yy1,’r-‘)is used to plot smoothed data using ”loess”’ method. A subplot(2,1,2) and plot(Y,y,’b.’,Y,yy2,’r-‘) is used to plot smoothed data using ”rloess” method.legend statement used to display data across the data.

Code:

clc ;
close all ;
clear all;
Y = (0:0.1:30)';
y = sin(Y) + 0.5*(rand(size(Y))-0.5);
y([90,110]) = 3;
yy1 = smooth(Y,y,0.1,'loess');
yy2 = smooth(Y,y,0.1,'rloess');
subplot(2,1,1)
plot( Y ,y,'b.',Y,yy1,'r-')
set(gca,'YLim',[-1.5 3.5])
legend('Original data','Smoothed data using ''loess''',...
'Location','NW')
subplot(2,1,2)
plot(Y,y,'b.',Y,yy2,'r-')
set(gca,'YLim',[-1.5 3.5])
legend('Original data','Smoothed data using ''rloess''',...
'Location','NW')

Output:

Matlab Smooth-1.1

So the smooth function get reduced the unwanted signal from the original signal. Fig 1 shows the graphs two graphs one is Original data and Smoothed data using the loss method. And another is Original data and Smoothed data using the loess method.

Example 2:

Let us see another example of a smooth function. The basically smooth function used for decreasing noise contain in the signals. In this example, we smooth a24-by-3 array count which contains counts at three intersections using smooth statement In this example data file (count.dat ) is loaded. Data with the noise is a parent in this data file. The 24-by-3 array count contains counts at three intersections. Thus, smoothing column wise gives a more meaningful picture of the count through each intersection. Here we use the moving average filter to smooth each column of the data separately with smooth function. Subplot and plot function used toplot the original data and the data smoothed by linear index and by each column separately. After that, we plot the difference between the two smoothed data sets that are A2 – A1. These two methods give different results near the endpoints. The title function is used for giving the title to the graphs. 

Code:

clc;
close all;
clear all;
load count.dat
A = smooth(count(:));
A1 = reshape(A,24,3);
A2 = zeros(24,3);
for I = 1:3
A2(:,I) = smooth(count(:,I));
end
subplot(3,1,1)
plot(count,':');
hold on
plot(A1,'-');
title('Smooth A1 (All Data)')
subplot(3,1,2)
plot(count,':');
hold on
plot(A2,'-');
title('Smooth A2 (Each Column)')
subplot(3,1,3)
plot(A2 - A1,'o-')
title('Difference A2 - A1')

Output:

Matlab Smooth-1.2
Categories
1. Basics of Matlab

Matlab File

In some applications, there is a need to access the text file to do operations like data reading, data writing. MATLAB FILE is used to do different options like write data to a text file or read data from text files, etc. For writing data on text files, we use fprint statements on Matlab. For reading data from a text file, we use a fscanf statement on Matlab. The specifying a type of access mode it would be either read(r) or write (w) we must use fopen statement.

Syntax:

The syntax for Matlab file handling operations is as shown below:-

For Write operation:

fprintf(fileID1,formatSpec,A1,...,An)
fprintf(formatSpec,A1,...,An)

For Reading operation:

A = fscanf(fileID,formatSpec)
A = fscanf(fileID,formatSpec,sizeA)
[A,count] = fscanf(___)

How does Matlab File work?

Matlab file is the file handling operations like read a file and write on the file. We see how these operations are work on Matlab.

For witting operations, there is some syntax which we use which are mentioned above. For writing, we take a variable and store some data which we want to write on that file and then we use a fopen statement, and in that, we specify the access type and the text file name and that stored in a file which is nothing but the file identifier. Then we use the writhing statement that is fprintf in that we mentioned the identifier name, data format, and that variable name that stored the data. And then we close that file using the fclose in that file identifier.

For reading operation, we first specify the access type and the file name by using a fopen statement stored in file identifier fileID1. Then we must specify the data format in formatSpec, and then we use fscanf statement to read data from a text file, in fscanf we take file identifier and format specifier, and data which we read from a text file is stored in one variable. Then we simply close the file using a fclose statement.

Examples to Implement Matlab File

Below are examples of Matlab File:

Example 1:

The first example we saw related to writing operations on a file. For that, we create one text file namely ‘textfile1’ with extension .txt. For writing some numbers on that file we can use a ‘rand’ function, basically, and is an inbuilt function available on Matlab this function is used to generate some random numbers. We use rand(5,1) it means the rand function can return five random numbers and multiply by 100 and these five numbers can store in x1 variable. Then we use a fopen statement to specify the file name and which operation we want to perform. For these, we write fopen and in parenthesis take file name (textfile1.txt) and we specify the type of access that is writing operation on file are denoted by ‘w’ these two arguments are separated by a comma and stored in variable fileID1.then using fprintf we can write these random numbers on the text file. And finally, close that file using a fclose statement. Then to verify we use the type function, a type is used to display the contents of the file.

Code:

x1 = 100*rand(5,1)
fileID1 = fopen('textfile1.txt','w');
fprintf(fileID1,'%f\n',x1);
fclose(fileID1);
type textfile1.txt

Output:

Matlab File1

Explanation: As we saw the result, the same random numbers are written in that text file. The file contents are displayed using the type function.

Example 2:

Let us see the example for a read operation, reading operation we take an earlier text file textfile1.txt, for a reading operation firstly we specify the type of access for that we use a fopen statement, we take fopen in parenthesis we take the text file name which we want to read (filetext1.txt) and the type of access that is reading the file which is specified by ‘r’ and these two arguments are separated by a comma. Then specify the format using ‘format spec’ we defined as afloat. Then we use a fscanf statement it is used for reading a text file. We take fsacf in parenthesis we write a fileID1 (text file is indicated by file identifier fileID1) and format specifier which we defined earlier that is formatSpec and these two arguments are separated by a comma. This read data is stored in variable A1. And we close the file using a fclose statement.

Code:

fileID1 = fopen('textfile1.txt','r');
formatSpec = '%f';A1 = fscanf(fileID1,formatSpec)fclose(fileID1);

Output:

read operation

Explanation: As we saw a result the data is displayed are similar to the earlier example result. That is shown as the read operation is successfully handled. Because read the same file which we write in an earlier example.

Example 3:

Let us see an example related to file handling operations, in this example, we read data from one file can that data write on another text file. For this we first read data from textfile1 using a fcanf statement then the same data can write on textfile2 file using a fprintf statement and after that, we close both the operation using a fclose. For verification, we use a type function this function is used to display the contents on file.

Code:

fileID1 = fopen('textfile1.txt','r');formatSpec = '%f';A1 = fscanf(fileID1,formatSpec)
fileID2 = fopen ('textfile2.txt','w');
fprintf (fileID2,'%f\n',A1);
fclose (fileID1);
fclose (fileID2);
type textfile2.txt

Output:

file handling operations
Categories
1. Basics of Matlab

Matlab File Extension

A file name extension or simply file extension is present as a suffix in the end of a file name and comes after a period (.) and is mostly 2 to 4 characters in length. We can easily notice these extensions while opening a picture or document, by checking the name of the file. Operating systems use file extensions to identify the applications that are associated with the file types i.e. it is identified which application will be opened when we double click on the file.

Below is the table showing some of the file extensions supported by MATLAB:

Content of the FileExtensionDetails
MATLAB formatted data.MATMATLAB workspace
TextTXT, CSV etcComma separated valuesDelimited valuesCombination of numbers and text
SpreadsheetXLSMXLSXXLSData stored in the excel
Extensible mark-up languageXMLFormatted text in XML
Image filesTifImage formats like ‘tif’, ‘jpeg’, ‘gif’ etc. are supported

Let us now understand the syntax to open or load some of these file extensions in MATLAB:

Syntax:

  • Load (file)
  • Imread (file)
  • readmatrix

Description:

  1. Load(file) is used to load the variables present in the input file with ‘.MAT’ extension into our workspace
  2. Imread (file) will read the image which is specified by the argument ‘file’. Since we have not passed any format argument in this syntax, it will infer the format from the contents of the file
  3. Readmatrix is used to open a spreadsheet or a file with extensions like ‘XLSM’, ‘XLSX’, ‘XLS’

Examples of Matlab File Extension

Let us now understand the code to read a file with .MAT extension in MATLAB using ‘Load(file) function’.

Example 1:

In this example, we will load data from a file ‘gong.mat’ which is present in MATLAB’s directory. Below are the steps to be followed:

  1. Check the existing contents of the workspace
  2. Check the contents of the ‘gong.mat’ file
  3. Load the ‘gong.mat file’

Code:

<!-- wp:paragraph -->
<p><code>disp('Before our file is loaded:')<br>whos</code>[Getting the existing contents of the workspace]</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><code>disp('gong.mat file:')<br>whos('-file','gong.mat')</code>[Getting the contents of the input file to be loaded]</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><code>load('gong.mat')</code>[Loading the file with .MAT extension]</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><code>disp('After our file is loaded:')<br>whos</code>[Checking the contents of the workspace after loading the file]</p>
<!-- /wp:paragraph -->

Input:

disp('Before our file is loaded:')
whos
disp('gong.mat file:')
whos('-file','gong.mat')
load('gong.mat')
disp('After our file is loaded:')
whos

Output:

Matlab File Extension-1.1

As we can see in the output, the contents of the file with .MAT extension are now loaded into our workspace.

Let us now understand the code to read a file with .tif extension. As this is an image file, we will be using ‘imread’ function.

Example 2:

In this example, we will read the image of a moon from the ‘moon.tif’ file which is present in MATLAB’s directory. We will follow the following 2 steps:

  1. Call the imread function; this will read the image
  2. Call the imshow function; this will display the moon’s image into our workspace

Code:

A = imread(‘moon.tif’)[Calling the imread function to read the file with ‘.tif’ extension]

imshow(A)[Calling the imshow function; the image read in the first step is passed as an input to the imshow function. This will display the image into our workspace]

Input:

A = imread(‘moon.tif’)
imshow(A)

Output:

Matlab File Extension-2.1
2.2

As we can see in the output, we have obtained image of the moon, which was read by us from MATLAB’s file with ‘.tif’ extension.

Let us now understand the code to read a file with .txt extension. We will use ‘readmatrix’ function for this purpose.

Example 3:

In this example, we will read contents of the file ‘basic_matrix.txt’ which is present in MATLAB’s directory.

Code:

A = readmatrix('basic_matrix.txt')[Calling the readmatrix function to read the file with ‘.txt’ extension] [‘basic_matrix.txt’ file contains a 5 x 4 matrix. The above line of code will display this matrix into our workspace]

Input:

A = readmatrix('basic_matrix.txt')

Output:

3.1

As we can see in the output, we have obtained a 5 x 4 matrix which is read by us from a file with ‘.txt’ extension.

Next, we will learn how to change a file’s extension. This can be done by following the below mentioned steps:

  • List all your files whose extensions you want to change in the directory
  • Put the extension as ‘.out’
  • Copy this file and then change its extension to the extension you want (for our understanding we will use ‘.txt’ extension)
  • Delete the file with .out extension

Below is the code to change the extension of multiple files in one go:

directory = 'C:\Users\name\Documents\MATLAB';
listOfFiles = dir([directory, '*.out']);

[Give the names of all the files whose extensions are to be changed]

for i = 1 :numel (listOfFiles)
file1 = fullfile(directory, listOfFiles(1).name);
[temporaryDir, temporaryFile] = fileparts(file1);
status = copyfile(file1, fullfile(temporaryDir, [temporaryFile, '.txt']))

[Loop to copy all .out files and give them ‘.txt’ extension]

delete(file)[Deleting the file with ‘.out’ extension]

end

Categories
1. Basics of Matlab

NUMEL Matlab

The NUMEL function is used to count the number of array elements. It is also used to count the number of elements in the database. The NUMEL performed in MatLab is employed to search out the number of elements in an array, The result of numel is the same as the prod(size(z)). We can count any number of elements from the database, there are no such criteria or requirements for database format. Any type of database is accessible to numel functions such as arrays, vectors, or multidimensional matrices.

Syntax:

The syntax of numel is given as follow: –

h = numel ( z )

How to Do NUMEL Matlab?

h = numel ( z )  returns the number of elements , z ,  in array h , equivalent to prod ( size ( z ) ) . In this format, h represents output variable name and z is the input variable name by using z we can pass any random database values to the function. And accordingly, it will create results in the form of several elements present at the input side.

Examples of NUMEL Matlab

Here are the following examples mentioned below.

Example 1:

Let us consider one example, firstly  Matrix, and then compute it using MatLab.

In this example, we have to create a 6 – by – 6 – by-2 matrix. To create Matrix have use numel function along with the magic Matlab function.

Code:

clc;
clear all;
h = magic( 5 );
h(:,:,2)=h'
n = numel( h )

Output:

e =  magic ( n )  returns an n-by-n matrix constructed from the integers 1 through n^ 2 with equal row and column sums. In the above example magic function is used to create a 6 – by – 6 – by – 2 matrices. As per that matrix h ( : , : , 1 )  and matrix h ( : , : , 2 )  is created . and then to count the number of elements in the matrix we used numel function. And the result is the total count of elements is 50.

Example 2:

Now let us consider the second example, we can create a cell array of character vectors, and then we can compute it to see the result in Matlab.  Here we use array a having n number of characters

Then to find how many elements are in the array we use numel Matlab function.

Code:

clc;
clear all;
d = {'Bing Cherry.',' Crab apples','orange.','Evergreen_Huckleberry'};
n =  numel( d )

Output:

Numel matlab output 2

In the above example, a cell array of character vector of fruits is given. All fruits are kept in set ‘d ’. To find the total numbers of fruits inset ‘ d ’ use Matlab function numel.

The total count of fruits inset ‘ d; is 4.

Example 3:

Let us consider another example; in this example, we can create one table of student information. These table fields are like student name, roll number, weight, height, and year. We can store the number of student information and as well we can also take this student information by the user instead of giving it directly in Matlab. After generating the table we can now use the numel Matlab function to see the number of elements in that table. And the result is stored in the variable ‘ z ’.

Code:

clc;
Name = {'Ram'; 'Raju'; 'Seeta'; 'Geeta'; 'Rani'};
Roll_no = [ 40; 30; 28; 48; 19 ];
Weight  =  [ 40; 55; 65; 85; 50 ];
Height = [ 170; 169; 140; 138; 175 ];
Year =  [ 2; 4; 1; 2; 3 ];
D = table(  Roll_no , Weight , Height,  Year , ' RowNames ' ,  Name )
Z = numel( D )

Output:

Numel matlab output 3
Categories
1. Basics of Matlab

Matlab Concatenate

Matlab Concatenate is used to combine 2 or more characters, strings, or elements of the array. It helps us in combining data present in different cells. Concatenation can also be used to combine 2 matrices and create a new matrix of larger size. It’s more like merging two data frames based on the need.

For example, at times we might need to combine ‘First Name’ and ‘Last Name’ present in different cells to get the complete name. In MATLAB we use ‘strcat’ and ‘cat’ function for concatenation.

In MATLAB, concatenation is of 2 types:

Horizontal concatenation: In this, 2 matrices are concatenated using commas.

Vertical concatenation: Here we concatenate our matrices using semicolons.

Syntax:

Below is the syntax for Matlab Concatenate:

C = strcat (st1, st2, st3, … stN)
C = cat(dim, x, y)

Explanation: C = strcat (st1, st2, st3, … stN) is used to concatenate the input strings horizontally. C = cat (dim, x, y) is used to concatenate matrix ‘x’ and matrix ‘y’ along the dimension ‘dim’.

Examples to Implement Matlab Concatenate

Let us now understand the code of strcat function in MATLAB using different examples:

Example 1:

In this example, we will learn how to concatenate character vectors. For our first example, we will follow the following steps:

1. Pass the required input character vectors

2. Input these character vectors in strcat function

Code:

St1 = 'let us learn'
St2 = ' concatenation'
St3 = ' in MATLAB'
C = strcat(St1, St2, St3)

Output:

Matlab concatenate1

Explanation: First, Declaring the first input character vector. Declaring the second input character vector. Declaring the third input character vector. Passing the input character vectors to the ‘strcat’ function. Please note that, in 2nd and 3rd input strings, we have passed an extra space in the beginning of the character. As we can see in the output, we have obtained a concatenated string of character vectors.

Example 2:

In this example, we will take cell arrays of characters will see how the strcat functions works. For this example, we will follow steps:

1. Initialize the input cell arrays

2. Pass the input cell arrays to the strcat function

Code:

Country = {'India','Canada', 'Sri Lanka'};
Capital = {'Delhi','Toronto', 'Colombo'};
C = strcat(Country, Capital)

Output:

Matlab concatenate2

Explanation: First, Declaring the first input character array. Declaring the second input character array. Passing the input character arrays to the ‘strcat’ function. strcat will concatenate the corresponding elements of 2 arrays. So, the 1stelement of ‘Country’ array will get concatenated with the 1st element of ‘Capital’ array. As we can see in the output, we have obtained a concatenated string of cell arrays as expected by us. We can also pass the input strings in reverse order if we expect the output to be in that order.

Example 3:

Code:

Country = {'India','Canada', 'Sri Lanka'};
Capital = {'Delhi','Toronto', 'Colombo'};
C = strcat(Capital, Country)

Output:

Matlab concatenate3

Explanation: First, Declaring the first input character array. Declaring the second input character array. Passing the input character arrays to the ‘strcat’ function. As we can see in the output, we have obtained a concatenated string of cell arrays as expected by us.

Example 4:

In this example, we will take the same example used above. We will also add a string ‘, Capital-Country after each concatenated element. This helps us in providing any extra information that we might need to pass. For this example, we will follow the following steps:

1. Initialize the input cell arrays

2. Pass the input cell arrays to the strcat function

3. Pass the string ‘, Capital-Country’ as the 3rd argument

Code:

Country = {'India','Canada', 'Sri Lanka'};
Capital = {'Delhi','Toronto', 'Colombo'};
C = strcat(Capital, Country, ', Capital-Country')

Output:

Capital Country

Explanation: First, Declaring the first input character array. Declaring the second input character array. Passing the input character arrays to the ‘strcat’ function. strcat will concatenate the corresponding elements of 2 arrays. The string ‘, Capital-Country’ is added to every element of the concatenated array. As we can see in the output, we have obtained a concatenated string of cell arrays with an additional string in the end of each element.

Example 5:

In this example, we will take two 3×3 matrices will see how the ‘cat’ functions works.

Code:

A = rand(3)
B = ones(3)
C = cat(1, A, B)

Output:

cat functions

Explanation: First, Declaring the first input matrix. Declaring the second input matrix. Passing the input matrices to the ‘cat’ function. For concatenation, the first argument can take 2 values. For vertical concatenation, first argument will be ‘1’. For horizontal concatenation, the first argument will be ‘2’. As we can see in the output, we have obtained vertically concatenated matrices.

Categories
1. Basics of Matlab

Matlab Surfc

Plots are the way of explaining the results graphically to the uninformed audience that doesn’t have any background knowledge about a particular topic. They are very helpful in explaining the outcome to the people who don’t have any prior knowledge in the technical front. There are multiple plots in Matlab which are used for various business purposes. Contour plots are the type of plots that are helpful in drawing the three-dimensional figures with the help of predictor variables (X and Y plane). Contour plots are also known as level plots. In this topic, we are going to learn about Matlab Surfc.

Working of surfc function in Matlab with Syntax

In Matlab, contour plots are used to plot the three-dimensional figures in the Z plane (response variable) with the help of predictor variables (X and Y). The three-dimensional figures that are plotted are known as contours. If we want to plot a contour plot under a surface plot, then we use surfc function in Matlab. Please find the below syntaxes which are used to plot the same:

  • surfc (a, b, c): This is used to plot a surface plot that is three-dimensional in nature and a contour plot underneath of it. The surface plot is a three-dimensional plot that has a surface that consists of edges and different face colors. The values in matrix c are plotted as heights that are above the grid in the x-y plane, whose values are given by the variables a and b.
  • surfc (a, b, c, color): This is used to draw the plot with the given surface color.
  • surfc(c): This is used to plot a surface and contour plot with the values specified as the row and column elements in c as the (x, y) coordinates.
  • surfc (axes value, ___): This will produce a plot with the axes value as specified, without working with the current axes value.
  • surfc (___, Name of the property, value of the property): This syntax is used when we want to use any property of the plot and make the necessary customizations to the plot. We can assign the name of the property and the value to it according to the business requirements.

Examples of Matlab Surfc

Please find the below examples depicting the use of surfc function in Matlab:

Example 1:

To display the contour plot under the surface plot with the help of matrices.

[a,b] = meshgrid(1:0.4:5,1:10);
c = cos(a) + sin(b);
surfc(a,b,c)

Output:

matlab surfc output 1

In the above example, the matrices are given as input and the contour plot is plotted under the surface plot. The surface of the respective plot takes the values of the function for its color and height.

Example 2:

To show the use of the color map while plotting the contour plot under the surface plot:

[a,b] = meshgrid(-2:.115:2);
c = peaks(a,b);
d = a.*b;
surfc(a,b,c,d)
colorbar

Output:

matlab surfc output 2

In the above example, we have assigned a new variable ‘d’ to use the colors in the surface and contour plot. The surface plot is plotted using the height values which is given by variable ‘c’. After using colormap, it should be noted that the size of c and d are the same. In the last part, we have added a colorbar to the plot to show how the values of colormap and values in variable ’d’ correspond to one another.

The first and the second input values i.e. ‘a’ and ‘b’ as used in the above syntax are the x and y coordinates which can be represented in the form of matrix or vector. If the values are represented in the form of a matrix, then it should be increasing or decreasing in one dimension and should remain constant in the other dimension. The function that is used to create the matrices for the input values can be achieved by using meshgrid function. If the values are represented in the form of a vector, then the values should increase or decrease. The third input value ‘c’ represents the height of the surface plot drawn at each x-y coordinate value. There should be at least two rows and two columns in it and is represented in the form of a matrix.

There are various properties of the plot that can be executed by the name and value of the property. Please find some of the below properties that can be used to customize the plots:

  • We can change the edge color of the plot using different values like flat, interp, or any RGB triplet value. If the value is given as ‘flat’ then there should be different colors for each edge which can be defined by the CData property. If the value is given as ‘interp’ then there should be interpolated colors for each edge which can be defined by the CData property. We can also assign the RGB value to the edges. RGB values determine the intensity level of Red, Green, and Blue.
  • We can also change the line style like solid, dashed, dotted or dash-dotted line, the dashed line being the default line style. The face color of the surface can also be changed with values like flat, interp, or any RGB value. If the value is given as ‘flat’ then there should be different colors for each surface which can be defined by the CData property. If the value is given as ‘interp’ then there should be interpolated colors for each surface which can be defined by the CData property. We can also assign the RGB value to the surfaces. RGB values determine the intensity level of Red, Green, and Blue.
  • We can also change the transparency level of each face which can be in a particular range from 0 to 1, flat, interp, or texturemap.

Example 3:

To plot the edge color of the plot to blue:

[a,b] = meshgrid(-4:.4:4);
c = a.*sin(b) - b.*cos(a);
s = surfc(a,b,c,'EdgeColor','b');

Output:

output 3
Categories
1. Basics of Matlab

Matlab Colorbar

‘Colorbar’ function is used to give the scale of the specific range of the object in the form of colors. In the colorbar, there are various properties that give additional features to the color scale. Properties of the color bar are location, name, value, target, off, target off, etc. By default color bar shows scale on the right side of the graphical plot. We can change the position of the colorbar by giving commands like north outside, west outside, east outside, south outside. By using the commands’ name and value, we can give a title to the color bar and we can change the appearance of the color bar. This function is mostly used for plots like contour, surf, mesh, etc. In this topic, we are going ot learn about Matlab ColorBar.

Syntax:

  1. Colorbar
  2. Colorbar(location)
  3. Variable name =colorbar()

How does Colorbar works in Matlab?

Steps to use colorbar command –

Step 1: accept any plot or graph

Step 2: write color bar command and assign it to one variable

Step 3: apply properties of colorbar

Step 4: display figures.

The above steps are generalized steps to use colorbar we can modify the steps according to the need for development and presentation.

Examples of Matlab ColorBar

Here are the following examples mentioned below.

Example 1:

In example 1, the color bar function is directly applied to a variable, so we can see only the color bar column or bar without any graph. As we did not mention any location to the color bar, therefore, it will take by default location which is the right side of the plot. here line width is mentioned as 2.5. and in the command window we can, we can see by default and inbuilt properties of the color bar. Properties are line width is east outside limits are 0 to 1 , font size is 9 ,position is [ 0.5220 0.15 0.0376 0.7167 ] and unit is normalized.

Matlab code for example 1

a = colorbar ;
b = a.LineWidth
a . LineWidth = 2.5

Command window 

>> Untitled
b =    0.5000
a =
ColorBar with properties :
Location : ' eastoutside '
Limits :  [0 1] FontSize :  9
Position : [0.5220 0.15 0.0376 0.7167] Units : ' normalized '
Show all properties

Output:

Matlab ColorBar output 1

Example 2:

In this example, we used one inbuilt plot ‘surf ’.in the surf, there are peaks with different colors present in it. Color intensity shows values of peaks proportion. Here we did not assign any variable to the plot or color bar therefore we cannot display properties.

Matlab code for Example

clear all ;
clc ;
surf (peaks)
colorbar

Output:

Matlab ColorBar output 2

Example 3:

In example 3, we have used the inbuilt plot which is contour. In this example, we already declared the location of the color bar so it will take the position of the plot according to code. Here we have declared positions west outside, east outside, south outside, and north outside.

Matlab code for Example 3

contourf (peaks)
a = colorbar
a . Location = ' westoutside '
figure ( ) ;
contourf(peaks)
b = colorbar
b . Location = ' southoutside '
figure( ) ;
contourf(peaks)
c = colorbar
c . Location = ' eastoutside '
figure( ) ;
contourf(peaks)
d = colorbar
d . Location = ' northoutside '
figure( ) ;

command window –

>> Untitled
a =
ColorBar with properties :
Location :  ' eastoutside '
Limits :   [ -6.5466 8 ] FontSize :  9
Position :  [0.8202 0.1095 0.0476 0.8167] Units :  ' normalized '
Show all properties
b =
ColorBar with properties :
Location : ' eastoutside '
Limits : [ -6.5466 8 ] FontSize : 9
Position : [ 0.8202 0.1095 0.0476 0.8167 ] Units :  ' normalized '
Show all properties
c =
ColorBar with properties :
Location : ' eastoutside '
Limits :  [ -6.5466 8 ] FontSize :  9
Position : [0.8202 0.1095 0.0476 0.8167] Units :  ' normalized '
d =
ColorBar with properties :
Location : ' eastoutside '
Limits :  [-6.5466 8] FontSize :  9
Position : [0.8202 0.1095 0.0476 0.8167] Units :   ' normalized '
Show all properties

Output:

Matlab ColorBar output 3

Example 4:

In this example, we declared one more feature of color bar .mesh is the inbuilt plot in Matlab. Here we mentioned ticks and tick labels of the color bar. we can assign any range and any label to the color bar.

mesh(peaks)
colorbar ( ' Ticks ' , [-15, -10, -5, 0, 5, 10, 15] , . . .
' TickLabels ', { 'range 1' , 'range 2' , 'range 3' ,'range 4' ,'range 5' } )

Output:

Matlab ColorBar output 4
Categories
1. Basics of Matlab

Matlab string

Matlab string is used to represent data in a sequence of characters. It represents the data like text using string arrays instead of character format. It stores every element into a sequence format. In it, we can represent data like text, numbers, special symbols, date time, duration, or calendar duration array into a string array. Its function converts the data type from the input array to string array format. And if data is already into a string array, which represented numbers, then by using the double function we can convert it to a numeric array.

Syntax:

str = string(A)

str = string(D)

How string Data Type works in Matlab?

It is used for representing the input data into a sequence format. There are simple following steps for use of the Matlab string function.

  • Step 1: Load the data which can be of any format.
  • Step 2: Use the appropriate syntax.
  • Step 3: Execute the Matlab code for getting output.

Examples of Matlab string:

Given below are the examples mentioned:

Example 1:

In this example, we can convert a text array into a string array using the Matlab string function and then we measure the size of that array. It is used for representing the input data into a sequence format. So first you take data which can be in different formats like text, numbers, special symbols, date time, duration, or calendar duration array and that data can be represented in string format using function. In this example, we take data which is into the text array format. Then we create an array that includes the words in text format. “A = [‘ Have ‘, ‘ A ‘, ‘ nice ‘, ‘ day’ ];” this line creates a text array of the word. So there are a total number of words is 4 into a text data into an array. As we know that to convert the text array into the string array we use the function. Then we use a function with proper syntax to convert the input array to a string array. “str = string(A)” this syntax is used for converting the input array to a string array.

Code:

clc;
clear all;
close all;
A = ['Have',' A',' nice',' day'];
str = string(A)
st = size(A)

Output:

Matlab string 1

After executing the Matlab code the input array is converted into a string array and generated array.

Example 2:

In this example, we can convert the duration array into a string array using Matlab string function. As we know that it is used for representing the input data into a sequence or string format. So first you take data so here data is in the duration format. For that, we create a duration array. “D = hours (20:25) + minutes (28) + seconds (2.2345);” this line is used to get the data into the duration array. The data is in duration array which includes hours, minutes, and seconds type of data. As we know that to convert the duration array into the string array we use the function. Then we use a function with proper syntax to convert the duration array to a string array. “str = string(D)” this syntax is used for converting the input array to a string array, where D is duration array. “str” is created string array.

Code:

clc;
clear all;
close all;
D = hours(20:25) + minutes(28) + seconds(2.2345);
str = string(D)

Output:

Matlab string 2

After executing the Matlab code string array is created into the command window.

Example 3:

In this example, we can convert the character vector into a string array using the Matlab string function. So first you take data. So here data is in the format of a character vector. “A = [‘MATLAB is a multi-numerical environment.’];” this line assign character vector to variable A. Then we use the function with proper syntax to convert the duration array to a string array. “str = string(A)” this syntax is used for converting the Character Vector to a string array, where A is Character Vector and “str” is created string array.

Code:

clc;
clear all;
close all;
A = ['MATLAB is a multi-numerical environment.'];
str = string(A)
c = size(A)

Output:

multi-numerical environment
Categories
1. Basics of Matlab

String to Number

In Matlab, str2num and str2double function is used for a string to number conversion. The function is used to convert text or string to a numeric value called as str2num function. The str2num function supports one or more numbers separated by spaces, decimal point, and commas. The input string can also include signs like the ‘+’ sign and ‘–‘ sign, the letter e or d preceding power of 10 scales factor and letter i or j for indicating the complex or imaginary number.str2num also converts string matrix to numeric matrix. If the input string does not contain a valid number in the matrix, str2num(str) returns the empty matrix.

Syntax:

The syntax for Matlab string to numbers as shown below:-

  • x1 = str2num(chr)
  • [ x1,tf] = str2num(chr)
  • x1 = str2double(str)

How to Domatlab String to Number?

Basically, now we can see how to convert a string into numbers for this, we can use a Matlab command str2num, the cell arrays, non-scalar string arrays it does not convert into numerical data type using a str2num function, and it is also sensitive spacing around to operators to avoid this error we use a str2double command.   The steps to convert a string into a number are as follows:-

Step 1: First, we take a char string into a variable

Step 2: use a command to convert a string into a number

Step 3: it’s an optional step to check the data type of object; this step we can perform   

Examples of Matlab String to Number

Different examples are mentioned below:

Example 1:

In this example, we have seen that how to convert string data to a number data type, so firstly we write a variable ‘a1’, and in that variable, we write anything or numbers in our case, we write numbers, the numbers are 15 81022 in single inverted, the numbers are assigned to variable ‘a1’. Then we find its class for that we write a class function with a variable name, class (a1). It’s a character, but actually, it’s a string of characters. Then we convert this string into the integer or numerical data type; the command converted to integer is str2num, str2num simply means that we are converting string to the numerical data type, so we simply write str2num(a1). And then we see a result in the numbers, so for verification, we see its data type with the command class, as we saw class returns the class of that given object and then we can verify that it converts the string data into a numerical data type or an integer data type. So we write a class of ans because now the answer is in ans, so we write a class (and), and we can see a data type; it will be numerical data type.

Code:

clc;
clear all;
close all;
a1 = '15781022'
class (a1)
str2num (a1)
class (ans)

Output:

matlab string to number output 1

As we saw a result on the command window, the first data type is char that is nothing but a string of character, and then after applying str2num, you see a data type as double it is nothing but numerical data type. So we prove that the string is converted into numbers.

Example 2:

Let us see an example; in this example, we pass a string with some alphabets and special character; then in 1st case, we have seen the result as x1 is an empty matrix and tf1 is a 0 it indicates that the status of conversion that fails. The cell arrays, non-scalar string arrays it does not convert into numerical data type using a str2num function, and it is also sensitive spacing around to operators. So in the 2nd statement, we remove that alphabets and special character into that string, then str2num function returns ax1 is not an empty matrix, written numbers on it, and the tf1 is ‘1’ it indicates that the conversion is successful.

Code:

clc;
clear all;
close all;
[ x1,tf1 ] = str2num('123 m/s, 593 m/s')[ x1,tf1 ] = str2num('123, 593')

Output:

matlab string to number output 2

As we saw a result, there is a drawback of str2num function, the cell arrays, non-scalar string arrays it does not convert into numerical data type using a str2num function, and it is also sensitive spacing around to operators or if we used then the conversion is failed, or it will return empty matrix. So this can avoid if we use a str2double function for conversion.

Example 3:

In this example, we convert the string call into double-precision values using a str2double command. First, we take a string cell into an str1 variable, then we check a data type of str1 using a class function, and then we convert that cell into a numerical data type by using a str2double command, and for verification purposes, we again use a class function.

Code:

clc;
clear all;
close all;
str1 = string({'10', '55', '88', '8', '87'; '88', '456', '100', '65', '5'})class (str1)x1 = str2double(str1)class (x1)

Output:

output 3

                                       

Categories
1. Basics of Matlab

Matlab Matrix Inverse

The following article provides an outline for Matlab Matrix Inverse. Inverse to any matrix, ‘M’ is defined as a matrix which, when multiplied with the matrix M, gives an identity matrix as output. The inverse matrix is represented by the notation M–1. So, as per the definition, if we multiply M with M–1 we will get an identity matrix in the output. The pre-requisite for a matrix to have an inverse is that it must be a square matrix, and the determinant of the matrix should not be equal to zero.

Syntax of getting Inverse of a Matrix in Matlab:

I = inv (M)

Description:

  • I = inv (M) is used to get the inverse of input matrix M. Please keep in mind that ‘M’ here must be a square matrix.

Examples of Matlab Matrix Inverse

Given below are the examples of Matlab Matrix Inverse:

Example 1:

In the first example, we will get the inverse of a 2 X 2 matrix.

Below are the steps that we will follow for this example:

  • Define the matrix whose inverse we want to calculate.
  • Pass this matrix as an input to the inverse function.
  • Verify the result by multiplying the input matrix with the output matrix. This should give an identity matrix as an output.

Code:

M = [3 2 ; 2 1];[Creating a 2 X 2 square matrix]

I = inv(M)[Passing the input matrix to the function inv] [Please note that, since we have used a 2 x 2 matrix as the input, our output matrix will also be a 2 X 2 matrix. This, when multiplied with the input matrix, will give an identity matrix as the output]

I*M[Code to verify that ‘I’ is inverse of ‘M’. This should give an identity matrix as the output]

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

Input:

M = [3 2 ; 2 1];
I = inv(M)
I*M

Output 1: (Inverse matrix)

Matlab Matrix Inverse 1

Output 2: (This should be an identity matrix)

This should be an identity

As we can see in the output 1, the function ‘inv’ has given us the inverse of the input matrix. Output 2 verifies that ‘I’ is the inverse of ‘M’.

Example 2:

In this example, we will get the inverse of a 3 X 3 matrix.

Below are the steps that we will follow for this example:

  • Define the 3 X 3 matrix whose inverse we want to calculate.
  • Pass this matrix as an input to the inverse function.
  • Verify the result by multiplying the input matrix with the output matrix. This should give an identity matrix as an output.

Code:

M = [3 2 3; 4 2 1; 3 4 1];[Creating a 3 X 3 square matrix]

I = inv(M)[Passing the 3 X 3 input matrix to the function inv] [Please note that, since we have used a 3 x 3 matrix as the input, our output matrix will also be a 3 X 3 matrix. This, when multiplied with the input matrix, will give an identity matrix as the output]

I*M[Code to verify that ‘I’ is inverse of ‘M’. This should give an identity matrix as the output]

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

Input:

M = [3 2 3; 4 2 1; 3 4 1];
I = inv(M)
I*M

Output 1: (Inverse matrix)

Matlab Matrix Inverse 3

Output 2: (This should be an identity matrix)

This should be an identity

As we can see in the output 1, the function ‘inv’ has given us the inverse of the input matrix. Output 2 verifies that ‘I’ is the inverse of ‘M’.

Example 3:

In this example, we will get the inverse of a 4 X 4 matrix.

Below are the steps that we will follow for this example:

  • Define the 4 X 4 matrix whose inverse we want to calculate.
  • Pass this matrix as an input to the inverse function.
  • Verify the result by multiplying the input matrix with the output matrix. This should give an identity matrix as an output.

Code:

M = [1 3 3 6; 4 2 8 2; 3 3 4 5; 2 6 3 1];[Creating a 4 X 4 square matrix]

I = inv(M)[Passing the 4 X 4 input matrix to the function inv] [Please note that, since we have used a 4 x 4 matrix as the input, our output matrix will also be a 4 X 4 matrix. This, when multiplied with the input matrix, will give an identity matrix as the output]

I*M[Code to verify that ‘I’ is inverse of ‘M’. This should give an identity matrix as the output]

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

Input:

M = [1 3 3 6; 4 2 8 2; 3 3 4 5; 2 6 3 1];
I = inv(M)
I*M

Output 1: (Inverse matrix)

Matlab Matrix Inverse 5

Output 2: (This should be an identity matrix)

Matlab Matrix Inverse 6

As we can see in the output 1, the function ‘inv’ has given us the inverse of the input matrix. Output 2 verifies that ‘I’ is the inverse of ‘M’.