Categories
2. After the Advance

Matlab Read CSV

Matlab provides different options to users; the read CSV is one of the options in Matlab. Suppose we need to store plain text and you are familiar with the comma separated format. At that time we can use CSV file format. Basically, CSV file format is human-readable well as it is compatible with different types of software applications such as Matlab. Because of this reason, the CSV file format is widely used and Matlab provides the different types of predefined functions for reading the records from the CSV file. There are several options available in Matlab for reading CSV files as per our requirement we can use respective options.

Syntax:

M = csvread (specified csv file name)
M = csvread (specified csv file name, row offset 1, column offset 1)
M = csvread (specified csv file name, row offset 1, column offset 1,[ row offset 1 column offset 1 row offset 2 column offset 2])

Explanation:

Basically, there is multiple syntaxes to read CSV files in Matlab as shown. In the first syntax, we use a simple syntax to read CSV files, here M is used for an array that must contain integer values, and specified CSV file name means actual file name that we need to read in Matlab.

In the second syntax additionally provides the offset value to the array. That means first-row offset and first column offset for example we can specify the starting value like 0, 0 in the file.

In the third syntax, we provide the range of offset value that means the bounded value that means row offset 1 and row offset 2 as well as we also provide column offset 1 and column offset 2. For example, we can specify the range instead of row values.

How to read CSV in Matlab?

Now let’s see how we can read the CSV file in Matlab as follows. Basically, we can use three different functions to read CSV files in Matlab as follows.

1. Read CSV file by using readtable() function:

This is the first way to read a CSV file in Matlab. In which that readtable() function reads all records from the file and saves them into the table and that table has a column name. if the CSV file does not have any heading for the column at that time readtable() function is assigned by default variable name for column and it starts from var1.
For example: info = readtable(specified CSV file name with extension)

Explanation:

In the above example, we use the array name for that info and after that, we use readtable() function with a specified CSV file name as shown in the above example.

2. Read CSV file by using readmatrix() function:

This is another way to read a CSV file in Matlab, in which we can read records from the CSV file into a matrix form.
For example: info = readmatrix(specified CSV file name with extension)

3. Read CSV file by using readcell() function:

By using this function we read records from a CSV file into a cell format.

For example: info = readcell(specified CSV file name with extension)

Examples:

Now let’s see the different examples of reading a CSV file in Matlab as follows. First, we need to create a new CSV file, here we created a program2.csv file and we added some value as shown in the below screenshot as follows.

matlab 1

Now create a new script and below code as follows.

A = readtable('program2.csv')
disp(A)

Explanation:

In the above example, we use readtable() function to read records from the program2.csv file, after that, we display that array by using disp () function as shown in the above example. The final output of this program we illustrated by using the following screenshot as follows.

matlab 2

See in above screenshot it takes by default column name var1, var2, and var3. If we need to print the specific range then we can use the following code as follows.

A = readtable('program2.csv','range','A1:B1')
disp(A)

Explanation:

In the above program, we use the readtable() function with a specific range option as shown. In this example, we provide a specified range that is A1:B1. The final output of this program we illustrated by using the following screenshot as follows.

Matlab Read CSV

Sometimes we need to print the specified portion of records at that time we can use the readtable() function with different options. Matlab provides the ReadVariableNames(), by using this option we can specify the first row from the csv file. When we use this option then we can easily determine which variable is imported or not.
Now let’s see another example of the readmatrix() function as follows.

Here we use an already created CSV file that we used in the above example.

A = readmatrix('program2.csv')
disp(A)

Explanation:

In the above example, we use the readmatrix () function and here we pass a CSV file that is a program2.csv file. Here we can also use the detectImportOptions() function and it is used to detect and import the specified option that we require. With this function, we can also use the range option as per our requirement. The final output of this program we illustrated by using the following screenshot as follows.

Matlab Read CSV 1

Now let’s see the third option to read the CSV file in Matlab as follows.

Matlab provides the third function to read the CSV file that is readcell() function. By using this function we can read the records from the CSV file and save into a cell format. Let’s see an example as follows.

A = readcell('program2.csv')
disp(A)

Explanation:

In the above example, we use readcell() function, by using this function we can read records from a CSV file and store them into the cell. The final output of this program we illustrated by using the following screenshot as follows.

Matlab Read CSV 2

As per our requirement, we can provide the range inside the function to fetch the specified records.

Categories
2. After the Advance

MATLAB Export Data

Export is the MATLAB function that is used to export the data from the Workspace. You can export variables from the MATLAB workspace to various file formats like .txt, jpg, Excel sheet, etc. In many applications, we need various files or databases as an output. These kinds of applications won’t work or operate without export functions. All types of data can export by using the export function in Matlab. Basically, data is exported in Workspace. Then that data can be exported to the destination. Along with the export function, we can give the name of the file which we are going to use in our program.

How to Export Data from MATLAB?

To export data from MATLAB we have different ways like we should export data to Microsoft excel file, we should export the data to a text file, and so on.

There is a simple step to export the data.

  • Write the data into the script.
  • Load the data to the workspace.
  • After loading data exporting the data to the desire destination.

Export Data Methodologies

Given below shows export data methodologies:

Example 1:

Let’s see example with Export Data to Excel sheet.

In this example, we discuss how to export Simulink scope data to an Excel sheet file using the writeable command in Matlab. Basically, in this example, we take that Simulink and assign sine wave and plot scope into it. We export the data from that Simulink, which basically stores the time and signal value. Then we can take a variable namely ‘ Ta ’, in Ta we can store the exported data from Simulink, for exporting data we use a write table inbuilt function which is available in MATLAB. Then simply display that data into the excel sheet

Code:

Ta = table(ScopeData.time, ScopeData.signals.values)
writetable(Ta,'Book1.xlsx')

Output:

MATLAB Export Data 1

We saw that Matlab code for example and output in the command window. When we run the example table is created into the command window. The table contains the different readings of sine data created into the Simulink.

To export a table in the workspace to an Excel spreadsheet file, we use the writetable function.

MATLAB Export Data 2

We saw that Simulink window. In Simulink window, there is a sine wave connected to the normal scope. After running the Simulink we observed the sine wave signal at the scope. We saw that signal. We can export data from the workspace to any worksheet in the file at any location. But by default, writetable writes your table data to the first worksheet in the file, starting at cell A1.

Finally, the data of Simulink scope in the Matlab is exported to Excel file by using writetable function. The below figures show that the exported data is in the excel file.

MATLAB Export Data 3
MATLAB Export Data 4

Finally, the data of Simulink scope in the Matlab is exported to an Excel file.

The above fig shows that the exported data is into the excel file.

Example 2:

Let us consider another example of data exporting. Now we can export the tabular data from the MATLAB workspace into the file using the writetable function. We can create a simple table and write some additional points. After that export that data to the .txt file. Data can be exported from. txt file to further processing.

Steps to export the data to a text file:

  • Firstly we create the tabular data by using the MATLAB function.
  • After that, the tabular data is exported to the destination file using writetable function.

The writetable function help to export the data from workspace to file.

Code:

clc;
close all;
clear all ;
Size = [0.5;0.2;2;5.25;6.5];
Shape = {'rectangle';'Round';'square';'rectangle';'Round'};
Price = [10.3;13.49;10.70;12.30;16.9];
Stock = [396;702;445;191;572];
T = table(Size,Shape,Price,Stock)
writetable(T,'mydoc.txt');
type mydoc.txt

Output:

For example, we created the table and assigned that data to a variable then all data is passed to the mydoc.txt file.

we created the table

We saw that Matlab code for example and output in the command window.

Command Window

The above fig shows the exported data in the .txt file. This is the same data as the data in the table.

Categories
2. After the Advance

Matlab Import Data

Import is the MATLAB function which is used to import the data in different forms like txt, jpg, etc. Also, we can import the data from Clipboard using the import function. In many applications, we need various files or databases as input. These kinds of applications won’t work or operate without an import function. All types of input data is accessible in the import function. We can use text files, excel files, notepad, and also images in different formats. The basic syntax of the import function is ‘import data’. Along with import data, we can give the name of the file which we are going to use in our program.

Syntax:

There are following syntaxes to import the data into Matlab:

  • X = importdata( filename ), loads data into array X.
  • X = importdata( ‘-pastespecial’ ), loads data from the system clipboard not in the file.
  • X = importdata( ___, delimiterIn ), interprets delimiter Inas the column separator in ASCII file, filename, or the clipboard data. You can easily use delimiter In with any of the input arguments in the above syntaxes to import the data.

How to Create Matlab Import Data?

You can import data into MATLAB using different ways like

1. From a file

Do one of the following process to import data from a file:

  • Select Import Data on the Home tab, in the Variable section.
  • Double-click a file name to browser Folder.

2. From the clipboard

Do one of the following to import data from the clipboard:

  • Click on the Workspace browser title bar and then select Paste.
  • And Call import function with proper syntax.

Example to Implement Matlab Import Data

Below are the examples of Matlab Import Data:

Example 1: 

Let us see one example, in this example, we import an image and display it using the import data function. Basically in this example, we take that image name with extension take that name into a single inverted comma and assign it to the filename1. We import the data from that filename1 which basically stores the image. Then we can take a variable namely ‘ X’, in X we can store the imported data from filename1, for importing data we use an import data inbuilt function which is available on MATLAB. Then simply we display that image using image function, image function is used to display the image. We pass that variable which stores the imported data into image function to display the image.

Code:

clc ;
clear all ;
close all ;
X = importdata ( ' download.jpg');
Image(X)

Output:

Matlab Import Data Example 1

Explanation: As we seen the resultant image is the same as the original image. The resultant image is nothing but the imported data image which we store into the variable X.

After the example 1 we can see the  Import a Text File.

Example 2:

Let us see another example, in this example, we Import a Text File( mydoc01.txt) and Specify Delimiter and Column Header method “ using import data function. Basically, in this example, we take that filename with extension take that name into a single inverted comma and assign it to the filename1. We import the data from that filename1 which is basically stores the data. Then we can take a variable namely ‘ A ’, in A we can store the imported data from filename1, for importing data we use an import data inbuilt function which is available on MATLAB. Then simply we display that data, disp function is used to display the image. We pass that variable which stores the imported data into disp function to display the data

Code:

clc;
clear all;
close all;
filename = 'mydoc01.txt';
delimiterIn = ' ';
headerlinesIn = 1;
A = importdata(filename,delimiterIn,headerlinesIn);
for k = [3, 5] disp(A.colheaders{1, k})
disp(A.data[:,k])
disp(' ')
end

Output:

Matlab Import Data Example 2

 After the example 2, we can see the Import a Text File and Return Detected Delimiter method.

Example 3:

Let us see another example, in this example, we Import a Text File( mydoc01.txt) and Return Detected Delimiter method “ using import data function. Using a text editor, create a comma-delimited ASCII file called mydoc01.txt.

Code:

clc;
clear all;
close all;
filename = 'mydoc01.txt';
[A,delimiterOut]=importdata(filename)

Output:

Return Detected Delimiter Method Example 3
Categories
2. After the Advance

Matplotlib Scatter

Matplotlib Scatter, in this we will learn one of the most important plots used in python for visualization, the scatter plot. We will be making use of the matplotlib library of Python for this purpose. Before we start creating scatter plots, let us first quickly understand what scatter plots are.

Scatter plots: Scatter plots are used in data visualization to get an intuitive understanding of our data. With scatter plots we can understand the relation between 2 variables. These plots are also very powerful in understanding the correlation between the variables, which can further be used in statistical techniques like linear regression, multiple regression, etc.

How to Create Scatter plots in python using Matplotlib?

We will start by importing the required libraries

import numpy as np[importing ‘numpy’] import matplotlib.pyplot as plt[importing ‘matplotlib’]

Next, let us create our data for Scatter plot

A = 400
a = np.random.rand(A)[variable a with 400 random values] b = np.random.rand(A)[variable b with 400 random values] colors = (0,0,0)[this will set color of our plot]

Step 1: We are now ready to create our Scatter plot

plt.scatter(a, b, c = colors)[‘scatter’ is called using ‘plt’] plt.title('Let us learn scatter plot)     [‘title’ is called to set title of our scatter plot] plt.xlabel('x variable')[setting name of x-axis] plt.ylabel('y variable')[setting name of y-axis] plt.show()[displaying our scatter plot]

This is how our input and output will look like in python:

Code:

import numpy as np
import matplotlib.pyplot as plt
A = 400
a = np.random.rand(A)
b = np.random.rand(A)
colors = (0,0,0)
plt.scatter(a, b, c = colors)
plt.title('Let us learn scatter plot')
plt.xlabel('x variable')
plt.ylabel('y variable')
plt.show()

Output:

matplotlib scatter1

Explanation: For our plot, we have taken random values for variables, the same is justified in the output. As we mentioned in the introduction of scatter plots, they help us in understanding the correlation between the variables, and since our input values are random, we can clearly see there is no correlation.

Step 2: Next, let us take 2 different categories of data and visualize them using scatter plots.

import numpy as np[importing ‘numpy’] import matplotlib.pyplot as plt[importing ‘matplotlib]

Next let us create our data for Scatter plot

A = 50
a1 = (1 + 0.6 * np.random.rand(A), np.random.rand(A))[variable a1with 50 random values] a2 = (2+0.3 * np.random.rand(A), 0.5*np.random.rand(A))[variable a2with 50 random values]
data = (a1, a2)
colors = (“red”, “green”)   [Defining variable ‘colors’, for setting color of the categories] groups = (“Category 1”, “Category 2”)  [Defining variable ‘groups’, for creating the label]

Let us now create our plot

fig = plt.figure()
Z = fig.add_subplot(1, 1, 1, facecolor='#E6E6E6') [Setting the color of the plot as grey] for data, color, group in zip(data, colors, groups):[‘for loop’ to create the plot and set color, label] x, y = data
Z.scatter(x, y, c=color, label=group)
plt.title(‘Learning scatter plot')[‘title’ is called to set title of our scatter plot] plt.legend(loc=1)[‘loc’ is used to set the location of labels in the pot] plt.show()[displaying our scatter plot]

This is how our input and output will look like in python:

Code:

import numpy as np
import matplotlib.pyplot as plt
A = 50
a1 = (1 + 0.6 * np.random.rand(A), np.random.rand(A))
a2 = (2+0.3 * np.random.rand(A), 0.5*np.random.rand(A))
data = (a1, a2)
colors = ("red", "green")
groups = ("Category 1", "Category 2")
fig = plt.figure()
Z = fig.add_subplot(1, 1, 1, facecolor='#E6E6E6')
for data, color, group in zip(data, colors, groups):
x, y = data
Z.scatter(x, y, c=color, label=group)
plt.title('Learning scatter plot')
plt.legend(loc=1)
plt.show()

Output:

create plot

Explanation: So here we have created scatter plot for different categories and labeled them.

Example to Implement Matplotlib Scatter

Finally, let us take an example where we have a correlation between the variables:

Example 1:

Here we will define 2 variables, such that we get some sort of linear relation between them

a = [8,10, 14, 12,20,25,30, 44, 48,52, 32, 30,44, 40, 55,50]
b = [70, 100, 136,120, 200, 210, 250, 300, 310, 411, 373, 427, 400, 420, 500, 510]

colors = (0,0,0)[this will set color of our plot]

Let us plot our data now

plt.scatter(a, b, c = colors)
plt.title('Scatter plot showing correlation')[‘title’ is called to set title of our scatter plot] plt.xlabel('x variable')[setting name of x-axis] plt.ylabel('y variable')[setting name of y-axis] plt.show()[displaying our scatter plot]

This is how our input and output will look like in python:

Code:

import numpy as np
import matplotlib.pyplot as plt
a = [8,10, 14, 12,20,25,30, 44, 48,52, 32, 30,44, 40, 55,50] b = [70, 100, 136,120, 200, 210, 250, 300, 310, 411, 373, 427, 400, 420, 500, 510] colors = (0,0,0)
plt.scatter(a, b, c = colors)
plt.title('Scatter plot showing correlation')
plt.xlabel('x variable')
plt.ylabel('y variable')
plt.show()

Output:

linear relation

Explanation: We can clearly see in our output that there is some linear relationship between the 2 variables initially. While the linear relation continues for the larger values, there are also some scattered values or outliers.

Categories
2. After the Advance

Matlab xlswrite

Xls command is basically used for excel file operations, and xlswrite is used to write or interprets an excel file. Along with the command, we can give the file name whatever we want and decide or select which sheet we want for writing. There is one more parameter range that decides the limit of rows and columns which is to be used. In this topic, we are going to learn about Matlab xlswrite.

Syntax:

  • xlswrite(filename, A)
  • xlswrite(filename, A, sheet, xlRange )

How Does Xlswrite Functions Work in Matlab?

To write data on a Microsoft Excel worksheet, we use an xlswrite statement. A filename statement is used for the unique identification of the file. After the identification of the file, the data will be written to the Microsoft Excel worksheet with the help of the ‘xlswrite’ function.

The steps for writing data on Microsoft Excel worksheet using an xlswrite statement:-

Step 1: First, identify the file using the ‘filename’ statement.

Step 2: Then, we take input data into a variable

Step 3: Then, we use an xlswrite statement with proper syntax for writing data to Microsoft

Excel worksheet

Step 4: After executing the code in Matlab, the data is stored in a Microsoft Excel worksheet

Examples of Matlab xlswrite

Given below are the examples of Matlab xlswrite:

Example 1:

Let us see a simple example of the xlswrite statement. Basically, xlswrite is used to write data to the Microsoft Excel worksheet. For writing data on the Microsoft Excel worksheet, we use an xlswrite statement with proper syntax. A filename statement is used for the unique identification of the file. We use “filename = ‘data.xlsx’” to identification of the ‘data.xlsx’ file. The file with the ‘xlsx’ extension is nothing but a Microsoft Excel worksheet. We create a Microsoft Excel file with the name ‘data.xlsx’. Then we take a variable to store the input arguments. So we take a variable, namely D, and the input arguments are loaded into the variable. D = [98 96 93 91 86 93]  it assign the input values to the variable D. Now, we can write the data into the Microsoft Excel worksheet. To write the data, we use the xlswrite function. For the writing into the Excel file, “xlswrite(filename, D)”  syntax is used. After executing the file, the input data is written into the Microsoft Excel worksheet.

Code:

clc;
clear all;
close all;
filename = 'data.xlsx';
D = [98 96 93 91 86 93 ];
xlswrite(filename,D)

Output:

Command window:

Matlab xlswrite output 1

Example 2:

Let us see another example of the xlswrite statement. As we know, the xlswrite is used to write data to the Microsoft Excel worksheet. In this example, we can write the data to the specific address and the specific sheet also. In this example, we take readings for the voltage and frequency of the signal. Here ‘filename’ statement is used to the unique identification of the file. We use “filename = ‘readings.xlsx’ ” to identification of the ‘readings.xlsx’ file. The file with the ‘xlsx’ extension is nothing but a Microsoft Excel worksheet. We create a Microsoft Excel file with the name ‘data.xlsx’. Then we take a variable to store the input arguments. So we take a variable, namely G, and the input arguments are loaded into the variableG = {‘VOLTAGE’, ‘FREQUENCY’; 200,98; 225,99; 223,97}  it assigns the input values to the variable G. Now, we can select the sheet by using the syntax. Here we used a simple syntax “sheet = 2;” to select the second sheet. The xlRange function is used to give a specific location for the start of writing.  Now we can write the data into the Microsoft Excel worksheet. To write the data, we use the xlswrite function. “xlswrite(filename, G, sheet,xlRange)“ this line is used to write the input data to the Microsoft Excel worksheet. After executing the file, the readings are written into the given Microsoft Excel worksheet.

Code:

clc;
clear all;
close all;
filename = 'readings.xlsx';
G = {'VOLTAGE','FREQUENCY'; 200,98; 225,99; 223,97};
sheet = 2;
xlRange = 'D1';
xlswrite(filename,G,sheet,xlRange)

Output:

Command window:

Matlab xlswrite output 2

Example 3:

Let us see one more example of an xlswrite statement. In this example, we can write the data of the variable to the Microsoft Excel worksheet. In this example, we use the path to identify the file. Here we directly identify the Excel file. So first, we take one variable, namely b. Random data is stored into the variable b. After that, we use the xlswrite statement to write the data to the Excel file.

xlswrite(‘C:\Users\win-10\Desktop\temp.xlsx’,b,’ D5:m15′) is used to write the data stored into the variable b to the specified Excel file that is “temp.xlsx”. D5 and m15 are the starting and ending points for writing the data. After executing the code, the data into the variable b is written into the given Microsoft Excel worksheet with specified starting and ending points.

Code:

clc;
clear all;
close all;
b= rand(10);
xlswrite('C:\Users\win-10\Desktop\temp.xlsx',b,'D5:m15');

Output:

Command window:

output 3
Categories
2. After the Advance

xlsread Matlab

‘xls’ command is used in Matlab to import and export excel files into Matlab. We can create the excel files by using this command as well as we can read the excel files by using this commands. there are two operation in Matlab one is to create excel files and other is to read or open excel files. These commands are xlsread and xlswrite. Xlsread command is used to read or open the existing excel files in Matlab. Xlswrite command is used to write or create excel files in Matlab.by using xlswrite command we can also modify content of existing excel files. This command improves the adaptability of Matlab language by accessing data in other formats.

Syntax:

xlsread (filename)
xlsread (filename, parameters list)
xlsread (filename, [data])
xlsread (filename, sheet name)
xlsread (filename, range for columns or row)

How does xlsread Work in Matlab?

To read any excel file in Matlab first we need to create that file with some data in to it. There are various ways to write and read the excel files. These files can be written by sing parameter list, direct data, by giving sheet name, or by giving a range of the columns or rows.

Steps to read excel file in Matlab –

  • Clear workspace
  • Declare and assign data
  • Write into excel file by using ‘xlsread’ syntax( xlswrite (filename,[data])
  • Declare variable to read a file
  • Use xlsread read command by using syntax. ( xlsread (filename ) ).

Examples of xlsread Matlab

Following are the examples are given below:

Example 1:

In this example, excel file is ‘abc.xlsx’ and data added to the file is [ 13 ,42, 53 ]. So it create one excel file in current directory.

Matlab EditorCommand window
Clc ;xlswrite(‘abc.xlsx ‘,[13, 42, 53])xlsread (‘ abc.xlsx ‘)ans =13    42    53

Output:

xlsread Matlab-1.1

Example 2:

In this example input data is declared by using another variable, which is ‘data’ (data= [3 4  7 7;4 3 2 2;4 56 78 32]) . Data is written in ‘file1’.

Matlab EditorCommand Window
Clc ;Data = [3 4  7 7 ; 4 3 2 2 ; 4 56 78 32]xlswrite(‘ file1.xlsx ‘, data)xlsread (‘ file1.xlsx ’)data =3     4     7     74     3     2     24    56    78    32ans =3     4     7     74     3     2     24    56    78    32

Output:

xlsread Matlab-1.2

Example 3:

In this example input data is declared by using another two variables,  which is ‘data’ (data1= [3 54  47 ;4 33 22; 56 7 42;43 7 1] and data2=[56 4 2 ; 5 4 2; 67 4 1;1 01 1]. Data is written in ‘file2’.

Matlab EditorCommand Window
Clc ;data1= [3 54  47 ; 4 33 22; 56 7 42 ; 43 7 1]data2 = [56 4 2 ; 5 4 2 ; 67 4 1 ; 1 01 1]xlswrite(‘ file2.xlsx ‘ , [data1 ; data2])xlsread(‘ file2.xlsx ‘) data1 =3    54    474    33    2256     7    4243     7     1data2 =56     4     25     4     267     4     11     1     1ans =3    54    474    33    2256     7    4243     7     156     4     25     4     267     4     11     1     1

Output:

xlsread Matlab-1.3

Example 4:

In this example input data is declared by using another two variables ,  which is ‘data’ (data1= [3 54  47 ;4 33 22; 56 7 42;43 7 1]and data2=[56 4 2 ; 5 4 2; 67 4 1;1 01 1]). Data is written in ‘file1’.to read the file we use range function. By giving range to the specific file we can display only important data.

Matlab EditorCommand Window
Clc ;data1 = [3 54  47 ;4 33 22; 56 7 42;43 7 1]data2 = [56 4 2 ; 5 4 2 ; 67 4 1 ; 1 01 1]xlswrite(‘file2.xlsx’,[data1 ; data2])r = ‘ A3 : B2 ‘a = xlsread(‘file2.xlsx’, r ) data1 =3    54    474    33    2256     7    4243     7     1data2 =56     4     25     4     267     4     11     1     1r =A3:B2a =4    3356     7

Output:

Output-1.4

Example 5:

In this example input data is declared by using another two variables , which is ‘data’ (data1= [3 54 43 47 ; 4 33 32 22 ; 56 5 7 42 ; 11 23 7 1] and data2 =[56 4 2 4 ;0 5 4 2; 67 1 4 1;1 01 1 1 ]). Data is written in ‘file3’.to read the file we use range function. By giving range to the specific file we can display only important data. Here start range value and end range value is same to we can display only specific row or column by using this method.

Matlab EditorCommand Window
clc;data1= [3 54 43 47 ;4 33  32 22; 56 5  7 42;11 23 7 1]data2=[56 4 2 4 ;0 5 4 2; 67 1 4 1;1 01  1 1]xlswrite(‘file3.xlsx’,[data1;data2])r=’C:C’a=xlsread(‘file3.xlsx’,r) data1 =3    54    43    474    33    32    2256     5     7    4211    23     7     1data2 =56     4     2     40     5     4     267     1     4     11     1     1     1r =C:Ca =4332772441

Output:

Output-1.5
Categories
2. After the Advance

Impulse Response Matlab

The following article provides an outline for Impulse Response Matlab. Impulse response δ(t) of a system is defined as the output signal that results when an impulse is applied to the system. The impulse response of a digital filter is the output that appears from the unit impulse sequence. Understanding the property of the system impulse response of the system and frequency response of the system is very important. Impulse response δ(t) calculates the unit impulse response of a dynamic system model. Impulse response assumes initial state values are zero for state-space models. Impulse response used “impulse(sys)” to plot of dynamic system. For Impulse Response of digital filter “impz” statement is used.

Syntax:

The syntax for Impulse Response (dynamic system) Matlab is as shown below:

impulse(sys)

impulse(sys,t1)

impulse(sys1,sys2,...,sysN,t)

[y1,t1] = impulse(sys)

Y1 = impulse(sys,t1)

[y1,t1,x1,ysd] = impulse(sys)

The syntax for Impulse Response (digital filter) Matlab is as shown below:

[h1,t1] = impz(b1,a1)

[h1,t1] = impz(sos)

[h1,t1] = impz(d)

[h1,t1] = impz(___,n1,fs1)

How to do Impulse Response Matlab?

In matlab Impulse Response uses an “impulse (sys)” statement for dynamic system and for digital filter “impz” is used.

The steps for Impulse Response for dynamic system:

  • Step 1: First input argument is taken in the variables.
  • Step 2: Then we use “ss” statement.
  • Step 3: Then we use “impulse (sys)” to plot the impulse response.

The steps for Impulse Response for digital filter system:

  • Step 1: First input argument is taken in the variables.
  • Step 2: Then we defining a sample range for filter.
  • Step 3: Then we use “impz” to calculating an impulse response of digital filter.
  • Step 4: Use stem to plot the impulse response.

Examples of Impulse Response Matlab

Given below are the examples :

Example 1:

Let us see an example, in this example first we take a numerator and denominator of a system for numerator we use num1 notation and for denominator we use den1. In num1 we take coefficients are 0.9 -0.45 0.35 0.02 and in den1 we take coefficients are 1.0 0.71 -0.46 -0.62. And we are also defining a sample range into N1 variable, so N1 is equal to 50 that is 50 samples we need. Now calculate the impulse response the inbuilt function is available on Matlab that is impz, impz is used for calculating an impulse response of digital filter. So now we take impz (num1, den1, N1) and the response is stored in y1 variable. Now for plotting a graph we use a stem function, stem is used to plot a discrete time signal. So we take an n2 variable for mentioning a range of x axis that is samples so we take range from 0 to 50 with the difference with 1. So now we take stem (n2, y1),where n2 is a samples numbers and y1 is stored the impulse response. Now this we get a plot of impulse response.

Code:

clc;
clear all;
close all;
N1 = 50;
num1 = [0.9 -0.45 0.35 0.02];
den1 = [1.0 0.71 -0.46 -0.62];
y1 = impz (num1, den1, N1);
n2 = 0 : N1-1;
stem(n2, y1);
title ('Impulse Response of Digital Filter');

Output:

Impulse Response Matlab 1

Example 2:

Let us see an example, in this example we plot a 2nd order state – space model. We take a 4 variables a1, b1, c1 and d1 this are Nx– by-Nx real- or complex-valued matrix. In our example the a1 is [-0.55, -0.78; 0.78, 0], b1 is a [1, -2; 0, 2], c1 is a [1.96, 6.44] and value of d1 is zero. And these 4 variables are passed from ss function, ss is a state space model. sys2 = ss (a1,b1,c1,d1) creates the discrete-time state-space model object of the following form: x[n+1]=a1x[n]+b1u[n] and y[n]=c1x[n]+d1u[n]. And this assign to sys2. And then we plot the response using an impulse function, impulse is used to plot a response of dynamic system. And we store an impulse response result into an y1 and t1 variable, for this we take command as [y1, t1] = impulse (sys2), the impulse returns the output response in a y1 variable and the time vector in a t1 variable these two variables are used for simulation. And the size of y1 is displayed on command window using a size function, size (y1). And because of impulse function the response is displayed.

Code:

clc;
close all;
clear all;
a1 = [-0.55, -0.78; 0.78,0];b1 = [1,-2;0,2];c1 = [1.96, 6.44];d1 = 0;sys2 = ss(a1, b1, c1, d1);impulse (sys2)[y1, t1] = impulse (sys2);size (y1)grid on

Output:

Impulse Response Matlab 2

The impulse response of the first input channel is shown in left plot, and the impulse response of the second input channel is shown in right plot.

Categories
2. After the Advance

Nyquist Matlab

In this article, we will learn how to create a Nyquist plot in MATLAB. Nyquist plots find their utility in analyzing system properties, like phase margin, gain margin & stability. As we will move forward in the article, we will learn how to create simple Nyquist plots and also Nyquist plots with complex conditions.

Understanding of Nyquist Plot

Nyquist plots also known as Nyquist Diagrams are used in signal processing and control engineering for plotting frequencies. Nyquist diagrams are used commonly to assess the stability of systems and also to get feedback. Cartesian coordinates are used for Nyquist plots. On X-axis, we plot the real part of our transfer function and on Y-axis, we plot the imaginary part. To get a frequency plot, it is passed as a parameter and this results in a graph based on the frequency. Polar coordinates can also be used for Nyquist plots. Here, radical coordinates are used to represent the transfer function’s gain, and the corresponding angular coordinate is represented by the transfer function’s phase.

Syntax for Creating a Nyquist Plot in Matlab

nyquist(sys)

Nyquist  function in MATLAB helps us in creating a Nyquist plot, related to frequency response produced by a dynamic model.

Let us understand this clearly with the help of a few examples:

To draw a Nyquist plot, we will first create a transfer function as follows:

H = 70 / (s+5) (s+ 4)

Now, this is a simple example without any other condition.

We can write above system as:

H = 70 / (s^2 + 9s + 20)

This transfer function is then passed as an argument to our function ‘nyquist’
i.enyquist(H)

This is how our input and output will look like in MATLAB console:

Input:

H=tf([0 0 70],[1 9 20]);
nyquist(H)

Output:

nyquist matlab output 1

In the next example, we will see a Nyquist plot with a pole at the center/origin.

Here is our transfer function:

H = 40 / s^3 + 2s ^ 2 + 3s + 4

This transfer function is then passed as an argument to our function ‘nyquist’
i.enyquist(H)

This is how our input and output will look like in MATLAB console:

Input:

H=tf([40],[3 2 3 4]);
nyquist(H)

Output:

nyquist matlab output 2

The system represented by our transfer function is having a pole located at the origin. This signifies the requirement of the detour around this pole. This is not shown on the plot created by Matlab.  In a system like this where a detour is required around the pole, we must understand the result of the detour.  In our case, since we have a single-pole located at origin & the detour has its radius approaching ‘0’&moving in the counter-clockwise direction, we interpret that the missing part of the plot that MATLAB does not show is a semicircle. This semicircle lies at infinity and in the clockwise direction.

Let’s take another example with a different condition:

In this example, we will see a Nyquist plot with a double pole at the center/origin.

Here is our transfer function:

H = 5s + 20 / s^3 + 5s^2

This transfer function is then passed as an argument to our function ‘nyquist’
i.enyquist(H)

This is how our input and output will look like in MATLAB console:

Input:

H=tf([5 20],[1 5 0 0]);
nyquist(H)

Output:

output 3

As we can see from the plot obtained, the 2 branches are going off towards infinity.  Also, as we have a double pole at the origin, it can be inferred that a counter-clockwise detour of 180° around the origin is yielding a clock-wise detour of 360°.

Finally, let’s take an example where transfer function will have one pole in RHP and the pole will be stable:

Here is our transfer function:

H = 20s + 40 / s^2 - 8

This transfer function is then passed as an argument to our function ‘nyquist’
i.enyquist(H)

This is how our input and output will look like in MATLAB console:

Input:

H=tf([20 40],[ 1 0 -8]);
nyquist(H)

Output:

output 4

So, in this article, we learned how to create a Nyquist plot in MATLAB. We can create both stable and unstable plots in MATLAB. As an additional tip, please keep in mind that to display the real & imaginary part of our given frequency, we can activate the data markers in MATLAB. For this, we just need to click at any point on the curve.

Categories
2. After the Advance

Matlab Index Exceeds Matrix Dimensions Error

In MATLAB, ‘index exceeds matrix dimensions error’ is encountered when we try accessing an element in the array/matrix which is not in index or not present in the array/matrix. The simple way to resolve this error is by ensuring that we are trying to access the element which is present in the matrix or array. The length of the array should be greater than or equal to the index that we are calling or trying to access.

In the latest versions of MATLAB (Starting from R2018b), the error message is:

“Index exceed number of array elements”

Syntax:

If A is an array, then we access any element of it using the below syntax:

E = A(n)

where ‘n’ is the index of the element that we want to access.

If ‘n’ is greater than the number of elements in the array, then we get the ‘index exceeds matrix dimensions’ error in case of a matrix or ‘index exceeds the number of array elements’ error in case of an array.

Examples of Matlab Index Exceeds Matrix Dimensions

Let us now understand how we get this error in MATLAB and how to resolve it.

Example 1:

In the first example, we will create an array with 5 elements and will try accessing the 7th element of this array (which does not exist). This will result in an index exceed dimensions error. The steps to be followed for this example are:

  1. Initialize the array
  2. Try accessing the element which is out of index

Code:

A = [3, 5, 1, 7, 10]

[Creating the array with 5 elements]

E = A(7)

[Code to access the 7th element of the array A]

[Since the 7th element does not exist in array A, we will get the error message]

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

Input:

A = [3, 5, 1, 7, 10] E = A(7)

Output:

Matlab Index Exceeds Matrix Dimensions 1

As we can see in the Output, since we are trying to access an element that does not exist in the array, we got the error message. Now, to overcome this error, we must try accessing an element that is in the range, i.e for E = A(n), ‘n’ must be less than or equal to 5.

Example 2:

In this example, we will create a matrix of size 3 X 3 and will try accessing an element in the 4th row (which does not exist). This will result in index exceed dimensions error. The steps to be followed for this example are:

  1. Initialize the matrix
  2. Try accessing the element which is out of index

Code:

A = [3, 5, 1; 7, 10, 5; 3, 6, 9]

[Creating the matrix of the order 3 X 3]

E = A(4, 2)

[Code to access the 2nd element in the 4th row of the matrix A]

[Since the 4th row does not exist in the matrix A, we will get the error message]

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

Input:

A = [3, 5, 1; 7, 10, 5; 3, 6, 9] E = A(4, 2)

Output:

Matlab Index Exceeds Matrix Dimensions 2

As we can see in the Output, since we are trying to access an element that does not exist in the matrix, we got the error message. Now, to overcome this error, we must try accessing an element that is in the range, i.e for E = A(m, n), ‘m’ and ‘n’ must be less than or equal to 3.

Example 3:

In this example, we will create a matrix of size 4 X 4 and will try accessing an element in the 5th column (which does not exist). This will result in an index exceed dimensions error. The steps to be followed for this example are:

  1. Initialize the matrix
  2. Try accessing the element which is out of index

Code:

A = [3, 15, 10, 4; 4, 5, 8, 0; 13, 5, 7, 10; 3, 4, 1, 6]

[Creating the matrix of the order 4 X 4]

E = A(4, 5)

[Code to access the 4th element in the 5th column of the matrix A]

[Since the 5th column does not exist in the matrix M, we will get the error message]

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

Input:

A = [3, 15, 10, 4; 4, 5, 8, 0; 13, 5, 7, 10; 3, 4, 1, 6]
E = A(4, 5)

Output:

Matlab Index Exceeds Matrix Dimensions 3

As we can see in the Output, since we are trying to access an element that does not exist in the matrix, we got the error message. Now, to overcome this error, we must try accessing an element that is in the range, i.e for E = A(m, n), ‘m’ and ‘n’ must be less than or equal to 4.

Categories
2. After the Advance

Matlab Errorbar

Error bar is a vertical or horizontal line on any graph or plot with respect to errors. There are various ways to represent error bars with multiple variables. Error bars have some properties such as line width, line size, color, marker, and data. Line width represents the width of the error line. Line size decides the size of the error bar. by using the color option we can change the color of the error bar as red, blue, green, etc. marker is used to represents marks or points on plot and co-ordinates. We can adjust the position of error bar as per our need horizontal or vertical. In this topic, we are going to learn about Matlab Errorbar.

Syntax –

errorbar (x ,err)
errorbar (variable, error name)
errorbar (var1 ,var2 ,err)
errorbar (variable name 1, variable name2, error name)
e = errorbar (var1 ,var2 ,err)
error = errorbar (parameters, error name)
Marker = '*'
error name.marker = ‘mark symbol’
Marker Size = 25;
error name. Marker size =size
Color = 'green';
error name.color = color name

Why we use Matlab Errorbar?

In Matlab, the Error bar is used to draw vertical or horizontal lines on any plot. to represent errors graphically error bar is used. In which we can use various properties to display error graphs or error plots. we can change marker points by multiple symbols as well as we can change the size of that marker. Illustration of marker symbol and size is given in example four. By default color of the error, the bar is blue and the marker is ‘ * ’.

Examples of Matlab Errorbar

Here are the following examples of Matlab Errorbar mention below

Example 1:

Let us consider one example with a single variable ‘x ’. Values of ‘x ’ varies from 1 to 99 with a uniform distance of 15. And the error is applied on variable x as multiple of 2.

Code:

clear all;
clc ;
x = 1 : 15 : 99
err = 2 * ones(size(x))
errorbar ( x ,err)

Output:

Matlab Errorbar output 1

Example 2:

Let us consider two-variable var 1 and var 2 with random values varies from 10 to 100. And one error is applied on the plot with respect to variable 2 in multiples of eight.

Code:

Clc ;
clear all;
var1 = [ 23 43 22 12 14 32 76 56 32 34 ] var2 = [ 21 32 45 42 63 65 88 77 94 99 ] err = 8 * ones(size ( var2))
errorbar ( var1,var2,err)

Output:

Matlab Errorbar output 2

Example 3:

In this example, we assume two different continuous functions instead of variables. One function is line space stored in var 1 and the second function is trigonometric cosine function, which is stored in var 2.

Code:

var1 = line space (0, 5, 10)
var2 = cos (var1)
err = [4 3 2 4 6 3 2 2 2 1] e = errorbar (var1, var2, err)

Output:

output 3

Example 4:

In this example, we have used the properties of the error bar. for marker, we have assigned symbol ‘ * ’.marker size is 25 and the color assigned to the error bar is green.

Code:

Clc ;
clear all ;
var1 = [3 5 7 9 11] var2 = cos (var1)
err = [2 2 2 2 2 ] e = errorbar (var1, var2, err)
e .Marker = ' * ';
e .Marker Size = 25;
e .Color = ' green ';

Output:

output 4