Import Text Files

Text files 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 tabular data from text files into a table using the Import Tool or the readtable function.

Import Text Files Using the Import Tool

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

Import Text Files Using readtable

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

T = readtable('airlinesmall.csv');

Display the first five rows and columns from the table.

T(1:5,1:5)
ans =

  5×5 table

    Year    Month    DayofMonth    DayOfWeek    DepTime 
    ____    _____    __________    _________    ________

    1987     10          21            3        {'642' }
    1987     10          26            1        {'1021'}
    1987     10          23            5        {'2055'}
    1987     10          23            5        {'1332'}
    1987     10          22            4        {'629' }

Import Data from Text Files as Other Data Types

In addition to tables, you can import tabular data from a text file 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.

Data Type of Output Function
Timetablereadtimetable
Numeric Matrixreadmatrix
Cell Arrayreadcell
Separate Column Vectorsreadvars

See Also

|

Related Topics