Matlab with excel data

Main Content

Spreadsheets often contain a mix of numeric and text data as well as variable and row
names, which is best represented in MATLAB® as a table. You can import data into a table using the Import
Tool
or the readtable function.

Import Spreadsheet Data Using the Import Tool

The Import Tool allows you to import into a table or other data type.
For example, read data from the sample spreadsheet file
patients.xls as a table in MATLAB. Open the file using the Import Tool and select options
such as the range of data and the output type. Then, click the Import
Selection
button to import the data into the MATLAB workspace.

Import tool showing options to specify range of data, variable names row, and output type

Import Spreadsheet Data Using readtable

Alternatively, you can read spreadsheet data into a table using the
readtable function with the file name, for
example:

T = readtable('patients.xls');

You can also select the range of data to import by specifying the range parameter.
For example, read the first five rows and columns of the spreadsheet. Specify the
range in Excel notation as
'A1:E5'.

T = readtable('patients.xls','Range','A1:E5')
T =

  4×5 table

      LastName        Gender      Age              Location               Height
    ____________    __________    ___    _____________________________    ______

    {'Smith'   }    {'Male'  }    38     {'County General Hospital'  }      71  
    {'Johnson' }    {'Male'  }    43     {'VA Hospital'              }      69  
    {'Williams'}    {'Female'}    38     {'St. Mary's Medical Center'}      64  
    {'Jones'   }    {'Female'}    40     {'VA Hospital'              }      67  

Import Spreadsheet Data as Other Data Types

In addition to tables, you can import your spreadsheet data into the MATLAB workspace as a timetable, a numeric matrix, a cell array, or separate
column vectors. Based on the data type you need, use one of these
functions.

See Also

Import Tool | readtable

Related Topics

  • Read Spreadsheet Data Using Import Tool
  • Read Spreadsheet Data into Table
  • Access Data in Tables

  • Trial Software
  • Trial Software
  • Product Updates
  • Product Updates

Apply MATLAB analysis and visualization capabilities to Excel data

When it comes to data analysis and visualization, technical professionals who use Excel® often encounter functional limitations. MATLAB supplements the capabilities of Excel by providing access to pre-built mathematical and analysis functions, visualization tools, and the ability to automate your analysis workflows.

3 ways to use MATLAB and Excel together:

  • Import Excel data into MATLAB
  • Access MATLAB from Excel
  • Package MATLAB code as Excel add-ins

Import Excel Data into MATLAB

The Import Tool makes it easy to bring data from an Excel spreadsheet into MATLAB. It shows the data both as it exists in Excel and how it will be represented in MATLAB, and recommends the best format for the data in MATLAB. Data import can be integrated into an automated analysis workflow in MATLAB, either by using code automatically generated by the Import Tool, or by calling MATLAB commands readtable and xlsread directly.

Excel data is naturally represented in MATLAB as a table, which organizes tabular data into columns of a single variable.

Access MATLAB from Excel

Spreadsheet Link™ connects Excel with the MATLAB workspace, enabling you to access the MATLAB environment from an Excel spreadsheet. You can exchange data between MATLAB and Excel, taking advantage of the familiar Excel interface while gaining access to MATLAB algorithms in image processing, data analytics, and control engineering.

Package MATLAB Code as Excel Add-ins

With MATLAB Compiler™, you can package math, graphics, and user interfaces created in MATLAB as Excel add-ins to perform analyses with Excel. These Excel add-ins can be distributed royalty-free to users who do not have MATLAB, and require no VBA programming.

With the addition of MATLAB Compiler SDK™, you can deploy add-ins to MATLAB Production Server™ for multiple Excel clients to access your MATLAB algorithms. This deployment ensures that users access the latest version of your analytics automatically with updates made to the algorithms deployed on the server.


Examples and How To


Software Reference

See also:

desktop and web deployment,

creating MATLAB apps,

data analysis,

data science

MATLAB provides options to write a table, array, or matrix to Microsoft Excel spreadsheets. The function available to do so is the writetable () function. The general syntax for this function is:

Syntax:

writetable(<data>, <filename>, <optional_values>)

Now, in the following sections, we shall see how to write a table, an array, and a matrix into a spreadsheet.

Writing a Table to Excel Spreadsheet:

Firstly, we shall create a table and then write the same to an excel spreadsheet with the help of writetable function.

Example 1: 

Matlab

tab = magic(5);

tab = array2table(tab,"VariableNames",

["R1" "R2" "R3" "R4"  "R5"]);

disp(tab)

writetable(tab,'new.xls','FileType','spreadsheet')

The output of the above code will create a new excel sheet in the current folder.

In the above code, we create a table from magic with the variable names or table headers passed as a vector. Then, in the writetable function, we pass the table, and the file name to be used (if present then, it’ll overwrite the data. If not, then it will create a new file and then, it’ll create a new file). The next argument is a field type that decides the file type and the argument following it is the value for the same field; spreadsheet in this case.

Writing a Matrix to Excel Spreadsheet

In the above section, we discussed how to add a table to an excel sheet. In this section, we shall explore the writetable further by adding a matrix at specified cells in a spreadsheet. Let us see the same with the help of an example. 

To write numeric data into an excel sheet, we need can use the writetable function. We have to use another function, the writematrix function.

writematrix(<data>, <filename>, <optional_values>)

The syntax is the same as the writetable just the datatype changes to double, float, or int.

Example 2:

Matlab

tab = magic(5);

writematrix(tab,'new.xls','Sheet',2,'Range','C1')

Output:

In this code, we write the magic square matrix to an excel spreadsheet named new.xls. The following arguments define the sheet number and the starting cell where we want to write our matrix-formed data.

Writing a cell array (array of multiple data types) to an excel spreadsheet 

To write an array with both numeric and text data, we use the writecell() function. The syntax of the same is similar to writematrix and writetable however, the data type then changes to a cell array.

writecell(<data>, <filename>, <optional_values>)

In the following example, we will write a cell array to a new sheet in our new.xls spreadsheet. 

Example 3:

Matlab

arr = {'cell', 'array'; 1, 2; 23, 31};

writecell(arr,'new.xls','Sheet',3,'Range','C1:E2')

Output:

In this code, we are writing a 3×3 cell array to the spreadsheet in sheet 3 from a range of cells C1 to E2, this means that only as many elements as are specified in the range C1:E2.


Download Article


Download Article

Whether you are an experienced MATLAB user or a novice, you may not be fully aware of MATLAB’s graphing abilities. MATLAB allows you to easily customize, label, and analyze graphs, giving you more freedom than the traditional Excel graph. In order to utilize MATLAB’s graphing abilities to the fullest, though, you must first understand the process for importing data. This instruction set will teach you how to import and graph excel data in MATLAB.

  1. Image titled Import, Graph, and Label Excel Data in MATLAB Step 1

    1

    Open a fresh MATLAB Screen. To make the process of importing and graphing data easier, clear any text in the command window with the command clc.

  2. Image titled Import, Graph, and Label Excel Data in MATLAB Step 2

    2

    Open your desired Excel file. Be sure to record the name of the Excel file for later use.

    Advertisement

  3. Image titled Import, Graph, and Label Excel Data in MATLAB Step 3

    3

    Save the Excel file into your MATLAB folder. The pathway for the folder typically is: C:Users[your account name]DocumentsMATLAB. Be sure you save the file as an Excel Workbook in order to have the proper file format for the import. Once this step is complete, you should see your Excel file in the current folder section in MATLAB.

  4. Image titled Import, Graph, and Label Excel Data in MATLAB Step 4

    4

    Locate the columns that will be exported. Identify the range of each column to be exported. The range of the column is the first cell in a column to the last cell in a column. The proper format for this range is the first cell followed by a colon followed by the last cell (I.e. “B1:B30”)

  5. Image titled Import, Graph, and Label Excel Data in MATLAB Step 5

    5

    Import the data columns to MATLAB. Enter the command var = xlsread(‘filename’, ‘xlrange’); into the command window for each column you want to import. In this command:

    • Var is a variable name of your choice (Example: “x” or “y”)
    • Filename is the name of your excel spreadsheet
    • Xlrange is the range of the desired column in the form “X—:X—“,with X being the letter of the column followed by the cell number.
  6. Advertisement

  1. Image titled Import, Graph, and Label Excel Data in MATLAB Step 6

    1

    Create a graph. Enter the command p = plot(indep, dep1, indep, dep2) in the command window. In this command, indep is the independent variable and dep1 and dep2 are the dependent variables. If you wish to graph more than two dependent variables, follow the same format and add a dep3 variable. If you wish to graph only one dependent variable, only graph the first pair of x and y values (Example: plot(x, y1)).

  1. Image titled Import, Graph, and Label Excel Data in MATLAB Step 7

    1

    Change the line color. Enter the command set(p,’color’,’[Desired Color]’); into the command window to change all the graphed lines to the same color. In this command, p is a reference to the variable you set your plot equal to in step 6. If you wish to change the color of only one line enter set(p(x),’color’,’[Desired Color]’); into the command line. The x in p(x) is the number that corresponds to the order that the lines are plotted in (Example: y1 = p(1), y2 = p(2)).

  2. Image titled Import, Graph, and Label Excel Data in MATLAB Step 8

    2

    Change the line style. Enter the command set(p,’LineStyle’,’style’); into the command window to change all of the graphed lines to the same style. If you wish to change the style of one line only, enter the command set(p(x),’LineStyle’,’style’); into the command line. In this command, the x in p(x) corresponds to the number in which the lines were graphed (Example: y1 = p(1), y2 = p(2)). Common line styles include:

    • dashed lines= ‘—‘
    • dotted lines = ‘:’
    • solid line = ‘-‘
    • dash-dot line = ‘-.’
  3. Image titled Import, Graph, and Label Excel Data in MATLAB Step 9

    3

    Label your axis. To label the x-axis, enter the command xlabel(‘text’) in the command window. To label the y-axis, enter the command ylabel(‘text’) in the command window.

  4. Image titled Import, Graph, and Label Excel Data in MATLAB Step 10

    4

    Add a title to your graph. Enter the command title(‘text’) in the command window. The title will display at the top of your graph.

  5. Image titled Import, Graph, and Label Excel Data in MATLAB Step 11

    5

    Add text within the graph. If you wish to enter text near your graphed lines, enter the command gtext(‘text’). Once you enter the command, a cursor will appear on the graph allowing you to click the area you wish to apply the label. The label can be put anywhere in the graph space.

  6. Image titled Import, Graph, and Label Excel Data in MATLAB Step 12

    6

    Add grid lines to the graph. If you wish to put grid lines in your plot for easier reading, enter the command grid into the command window. Entering the command again will remove the grid lines.

  7. 7

    Save your graph. Click file on upper right hand side of the MATLAB graph screen followed by save as in the menu. Save the graph to the desired location.

  8. Advertisement

Image titled Import, Graph, and Label Excel Data in MATLAB Step 13

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Thanks for submitting a tip for review!

About This Article

Thanks to all authors for creating a page that has been read 65,042 times.

Is this article up to date?

This article is a quick tutorial on using the xlsread MATLAB command to import data from an Excel file into MATLAB. Specifically, you’ll learn to:

  • Extract data from Excel in MATLAB
  • Remove irrelevant content from your extract
  • Import data from a specific sheet
  • Select the Excel file to read
  • Extract different formats

How to Extract Data from Excel in MATLAB

Xlsread Basic Syntax

Here’s the basic syntax to import data from Excel into MATLAB:

[numbers text textAndNumbers] = xlsread(excelFileName)
  • numbers: numbers contained in your Excel file.
  • text: text contained in your Excel file.
  • textAndNumbers: text and numbers contained in your Excel file.

Xlsread MATLAB Example

First, let’s look at some details about how this works through an actual example. Let’s say I have the following Excel file named “excelFile.xlsx:”

Example of reading an Excel file using xlsread

Then, applying the previous basic syntax to read it, we get:

excelFileName = 'excelFile.xlsx';
[numbers text textAndNumbers] = xlsread(excelFileName);

So, let’s examine the outputs of the xlsread MATLAB command:
numbers of the Excel file exctracttext of the Excel file exctracttext and numbers of the Excel file exctract
As you can see, the three outputs are not of the same data type:

  • “numbers” is an array: this means that you can access the content of an element using parentheses: numbers(i)
  • “text” is a cell array: this means that you can access the content of a cell using braces: text{i}
  • “numbersAndText” is a cell array: this means that you can access the content of a cell using braces: numbersAndText{i}

Remove Irrelevant Content from Your Extract

  • Notice that for the “numbers” variable, the first and last rows have been removed, and the text has been replaced by “NaN” value. You can get rid of the “NaN” values with the following:
    numbers = numbers(~isnan(numbers)); % delete numbers that are not "NaN"

    The “numbers” variable then becomes:
    isnan MATLAB command example

  • The numbers contained in the “text” variable have been replaced by empty cells. You can get rid of the empty cells with the following:
    text = text(~cellfun('isempty', text)); % delete empty cells

    The “text” variable then becomes:
    remove empty cell from Excel file extract

Import Data from a Specific Sheet

What If the Content Is in Another Sheet?

Let’s use the previous Excel file “excelFile.xlsx” with the content on a sheet named “Sheet1” (which is the default name of a sheet if you create an Excel file).
Moreover, if you add a sheet to the Excel file, the name of the sheet will be “Sheet2.” So, let’s do that and move the first sheet (with the previous content) to the right of the second sheet and save the file:
finding a specific sheet using xlsread MATLAB command

Then, we’ll apply the xlsread MATLAB command as we did previously:

excelFileName = 'excelFile.xlsx';
[numbers text textAndNumbers] = xlsread(excelFileName);

By default, xlsread will read the sheet located at the very left of the Excel file, namely “Sheet2.”

xlsread extract of an empty sheet
Since “Sheet2” is empty, it makes sense that the extracted content is empty. So, how do you read “Sheet1”?

Finding a Sheet

First, there are two ways to specify the sheet to read using the xlsread MATLAB command:

  1. Using the number of the sheet:
    [numbers text textAndNumbers] = xlsread(excelFileName, sheetNumber);

    The number of the sheet is “2” here because we want to read the second sheet (counting from the left). So, giving the “sheetNumber” variable the value “1” is equivalent to not using the second argument of the xlsread MATLAB command. Here’s how to extract the desired sheet:

    sheetNumber = 2; % second sheet counting from the left
    excelFileName  = 'excelFile.xlsx';
    [numbers text textAndNumbers] = xlsread(excelFileName, sheetNumber);
  2. Using the name of the sheet:
    [numbers text textAndNumbers] = xlsread(excelFileName, sheetName);

    The sheet name in that example is “Sheet1,” so you can use it as the second argument if you want to extract the second sheet:

    sheetName = 'Sheet1';
    excelFileName  = 'excelFile.xlsx';
    [numbers text textAndNumbers] = xlsread(excelFileName, sheetName);

In both cases, if the sheet number or the sheet name you’re referring to doesn’t exist, you’ll get the following error:
Error in xlsread: Worksheet not found

Specific Problems and Solutions

Ask the User to Select an Excel File

Using the uigetfile MATLAB command, you can ask the user to find and select the desired excel file to be read:

[fileName, pathName] = uigetfile({'*.xlsx';'*.xls'}, 'Choose an Excel file');

You can then use the “fileName” and the “pathName” (respectively the name of the selected file and its location) to read your Excel file.
There are 2 ways of doing that:

  • Moving to the file’s location:
    [fileName, pathName] = uigetfile({'*.xlsx';'*.xls'}, 'Choose an Excel file');
    currentFolder = pwd; % save the current location
    cd(pathName)
    [numbers text textAndNumbers] = xlsread(fileName)
    cd(currentFolder);

    We use the pwd MATLAB command to save the current location from before, move to the Excel file’s location, perform the extraction, and move back to the initial location.

  • Specifying the location:
    [fileName, pathName] = uigetfile({'*.xlsx';'*.xls'}, 'Choose an Excel file');
    fullFileExcelFile = fullfile(pathName, fileName); % create the path to the Excel file
    [numbers text textAndNumbers] = xlsread(fullFileExcelFile);

    fullfile creates the path by adding ‘/’ or ‘’ between the file name and the path name (you could do it yourself with something like [pathName ‘/’ fileName], but this can be a little bit trickier depending on whether you use a UNIX or Windows platform).

Be Careful About the Format of the Cells You’re Extracting

First, if the numbers contained in your Excel file are formatted as strings, you’ll get a cell array when extracting. For example, by adding a single quotation mark to the left of every number in the Excel file “excelFile.xlsx” that we’ve used previously, we are formatting them as strings:Use numbers as string for the Excel file extractAnd if we import the data from the Excel file now, we get:
xlsread MATLAB extract empty numbersxlsread MATLAB text extract for string numbersxlsread MATLAB text and numbers extract for string numbers
Since the numbers have been formatted as strings in the Excel file, there are no numbers anymore, the “numbers” variable is empty and the “text” and “textAndNumbers” variables have become identical.

The Empty Cell Issue

If you have empty cells in your Excel file before the first row, the xlsread MATLAB command will get rid of them. This is a problem if you want to write the content back to the Excel file (e.g. to modify a value) because you won’t be able to know where to write it.

Unfortunately, there is no easy way to get that information using xlsread. If you have this issue, you can refer to this article for a workaround: https://realtechnologytools.com/matlab-row-number/

Key takeaways:

  • To read an Excel file, use:
    [numbers text textAndNumbers] = xlsread(excelFileName);
    • numbers: array of the numbers in the file, access an element using numbers(i)
    • text: cell array of the text in the file, access an element using text{i}
    • textAndNumbers: cell array of the text and numbers in the file, access an element using textAndNumbers{i}
  • To remove irrelevant values from your extract, use:
    numbers = numbers(~isnan(numbers)); % delete numbers that are "NaN"
    text = text(~cellfun('isempty', text)); % delete empty cells
  • To import a specific sheet in MATLAB, use:
    [numbers text textAndNumbers] = xlsread(excelFileName, sheetName); % use the sheet name
    [numbers text textAndNumbers] = xlsread(excelFileName, sheetNumber); % use the sheet number
  • There are 2 ways to ask the user to select an Excel file and read it:
    1. By moving to the file’s location:
      [fileName, pathName] = uigetfile({'*.xlsx';'*.xls'}, 'Choose an Excel file');
      currentFolder = pwd; % save the current location
      cd(pathName)
      [numbers text textAndNumbers] = xlsread(fileName)
      cd(currentFolder);
    2. By specifying the location:
      [fileName, pathName] = uigetfile({'*.xlsx';'*.xls'}, 'Choose an Excel file');
      fullFileExcelFile = fullfile(pathName, fileName); % create the path to the Excel file
      [numbers text textAndNumbers] = xlsread(fullFileExcelFile);
  • If the numbers in your Excel file are formatted as strings (e.g. using a single quotation mark at the left of a number in the Excel file), then they will be extracted in the “text” variable rather than in the “numbers” variable.

You can find more information about the xlsread MATLAB function in the MathWorks documation: https://fr.mathworks.com/help/matlab/ref/xlsread.html

If you want to learn more about the practical tips that helped me stop wasting time doing mindless work (such as working with Excel files and writing reports) I wrote a small reference book about it:

Понравилась статья? Поделить с друзьями:
  • Mathtype шрифт для word
  • Match the words to form column a with the word combinations
  • Match word for english study
  • Mathtype скачать для word на русском
  • Match the words more than one word is possible example to attend classes