Main Content

Import Numeric Data from Text Files into Matrix

Import numeric data as MATLAB® arrays from files stored as comma-separated or delimited text files.

Import Comma-Separated Data

This example shows how to import comma-separated numeric data from a text file. Create a sample file, read all the data in the file, and then read only a subset starting from a specified location.

Create a sample file named ph.dat that contains comma-separated data and display the contents of the file.

rng('default')
A = 0.9*randi(99,[3 4]);
writematrix(A,'ph.dat','Delimiter',',')
type('ph.dat')
72.9,81.9,25.2,86.4
81,56.7,49.5,14.4
11.7,9,85.5,87.3

Read the file using the readmatrix function. The function returns a 3-by-4 double array containing the data from the file.

M = readmatrix('ph.dat')
M = 3×4

   72.9000   81.9000   25.2000   86.4000
   81.0000   56.7000   49.5000   14.4000
   11.7000    9.0000   85.5000   87.3000

Import only the rectangular portion of data starting from the first row and third column in the file. Create an import options object and specify the columns and rows to import using the SelectedVariableNames and DataLines properties. Then, import the selected portion of the data from the file.

opts = detectImportOptions('ph.dat');
opts.SelectedVariableNames = {'Var3','Var4'};
opts.DataLines = [1 3];
readmatrix('ph.dat',opts)
ans = 3×2

   25.2000   86.4000
   49.5000   14.4000
   85.5000   87.3000

Import Delimited Numeric Data

This example shows how to import numeric data delimited by any single character using the writematrix function. Create a sample file, read the entire file, and then read a subset of the file starting at the specified location.

Create a tab-delimited file named num.txt that contains a 4-by-4 numeric array and display the contents of the file.

rng('default')
A = randi(99,[4,4]);
writematrix(A,'num.txt','Delimiter','\t')
type('num.txt')
81	63	95	95
90	10	96	49
13	28	16	80
91	55	97	15

Read the entire file. The readmatrix function determines the delimiter automatically and returns a 4-by-4 double array.

M = readmatrix('num.txt')
M = 4×4

    81    63    95    95
    90    10    96    49
    13    28    16    80
    91    55    97    15

Read only the rectangular block of data beginning from the second row, third column, in the file. Create an import options object and specify the columns and rows to import using the SelectedVariableNames and DataLines properties. Then, import the selected portion of the data from the file.

opts = detectImportOptions('num.txt');
opts.SelectedVariableNames = {'Var3','Var4'};
opts.DataLines = [2 4];
readmatrix('num.txt',opts)
ans = 3×2

    96    49
    16    80
    97    15

See Also

| | |

Related Topics