TExcelTAD
Home › MATLAB / Octave › Reading Numeric Data

Reading Numeric Data

Measurement files, simulation output and exported spreadsheets are mostly numbers stored as text. You could read them line by line and convert each piece (see Reading & Writing Text Files), but MATLAB has functions that turn a whole file of numbers into a matrix in one call. Which one to use depends on how regular the file is.

File looks like Use Returns
Only numbers, separated by spaces load(name) or load(name, '-ascii') A matrix
Numbers with a delimiter (, ; tab), maybe header rows dlmread(name, delim, r0, c0) A matrix (empty fields → 0)
A header, then numbers in a known layout fgetl for the header + fscanf(fid, fmt, size) A matrix
Columns of different types (text and numbers), missing values textscan(fid, fmt, options...) A cell array, one cell per column
Not sure; let MATLAB guess the header importdata(name) A struct with data, textdata, colheaders
Numbers inside a string sscanf(str, fmt), str2double(str) Numbers
Anything tabular (MATLAB R2019a+) readmatrix(name) A matrix (see CSV & Delimited Files)

Note: every example writes its own input file first, so you can see exactly what is being read.

The simplest case: load

A file that contains nothing but numbers in rows and columns, with spaces or tabs between them, is read by load. Lines starting with % are treated as comments, so a short description at the top is allowed:

matlab · try it yourself
fid = fopen('grid.txt', 'w');
fprintf(fid, '%% heights in metres, 3 rows x 4 columns\n');
fprintf(fid, '1.5 2.0 2.5 3.0\n2.0 2.5 3.5 4.0\n2.5 3.5 4.0 5.5\n');
fclose(fid);

H = load('grid.txt')
fprintf('size %d x %d, mean height %.3f m\n', size(H), mean(H(:)));
H =

   1.5000   2.0000   2.5000   3.0000
   2.0000   2.5000   3.5000   4.0000
   2.5000   3.5000   4.0000   5.5000

size 3 x 4, mean height 3.042 m

load fails if any line has a different number of values or contains text that isn't a comment. For those files, use one of the more flexible functions below. (Called as a command, load grid.txt also works, but then the variable is named after the file: grid.)

A header, then numbers: fgetl + fscanf

fscanf(fid, format, size) reads values matching format from the current position until the file ends (or the format stops matching). Reading the header line first with fgetl moves past it. The size argument [3 Inf] means "3 rows, as many columns as needed": fscanf fills the result column by column, so each line of the file becomes a column and you transpose at the end:

matlab · try it yourself
fid = fopen('sensor.txt', 'w');
fprintf(fid, 'time temp humidity\n');
fprintf(fid, '%d %.1f %d\n', [0 1 2 3; 20.5 21.0 21.4 22.1; 40 42 41 45]);
fclose(fid);

fid = fopen('sensor.txt', 'r');
header = fgetl(fid);                 % 'time temp humidity'
A = fscanf(fid, '%f', [3 Inf]);      % 3-by-N, one column per line
fclose(fid);
A = A'                               % back to one row per line
names = strsplit(header);
fprintf('%s ranges from %.1f to %.1f\n', names{2}, min(A(:, 2)), max(A(:, 2)));
A =

         0   20.5000   40.0000
    1.0000   21.0000   42.0000
    2.0000   21.4000   41.0000
    3.0000   22.1000   45.0000

temp ranges from 20.5 to 22.1

Forgetting the transpose, or giving [Inf 3], is the classic mistake here: the numbers come out in the wrong places without any error. If the number of values doesn't fill the last column completely, fscanf pads it with zeros, another reason to check the size of what you read.

Mixed columns and missing values: textscan

textscan is the most flexible reader. The format describes one line (%f a number, %d an integer, %s a word, %q a possibly quoted string, %*s skip a field), and the result is a cell array with one cell per column: numbers in numeric arrays, text in cell arrays of strings.

matlab · try it yourself
fid = fopen('people.txt', 'w');
fprintf(fid, 'Ada 36 1.68\nBoris 41 1.80\nChen 29 1.75\n');
fclose(fid);

fid = fopen('people.txt', 'r');
C = textscan(fid, '%s %d %f');
fclose(fid);
names = C{1};  ages = C{2};  heights = C{3};
fprintf('%d people, classes: %s, %s, %s\n', numel(names), class(names), class(ages), class(heights));
for k = 1:numel(names)
    fprintf('%-6s %3d years %5.2f m\n', names{k}, ages(k), heights(k));
end
3 people, classes: cell, int32, double
Ada     36 years  1.68 m
Boris   41 years  1.80 m
Chen    29 years  1.75 m

Note that %d gives int32, not double: arithmetic with it stays in integers (see Integers & Bitwise Operations). Use %f when you want ordinary doubles.

Name-value options handle the common messiness of real files:

Option Example Effect
'Delimiter' ',' Field separator (default: white space)
'HeaderLines' 1 Lines to skip at the start
'CommentStyle' '#' Ignore the rest of a line after this marker
'TreatAsEmpty' 'NA' Strings that mean "missing"
'EmptyValue' NaN (default) Value used for empty or missing numeric fields
matlab · try it yourself
fid = fopen('weather.csv', 'w');
fprintf(fid, 'day,temp,rain\n1,12.5,NA\n2,,0.4\n3,14.0,1.2\n# sensor reset\n4,13.1,0.0\n');
fclose(fid);

fid = fopen('weather.csv', 'r');
C = textscan(fid, '%f %f %f', 'Delimiter', ',', 'HeaderLines', 1, ...
             'TreatAsEmpty', 'NA', 'CommentStyle', '#');
fclose(fid);
W = [C{:}]                          % join the columns into one matrix
fprintf('missing values: %d, mean temperature %.2f\n', sum(isnan(W(:))), mean(W(:, 2), 'omitnan'));
W =

   1.0000  12.5000      NaN
   2.0000      NaN   0.4000
   3.0000  14.0000   1.2000
   4.0000  13.1000        0

missing values: 2, mean temperature 13.20

Missing fields become NaN, which arithmetic then propagates; mean(..., 'omitnan') ignores them. Compare dlmread below, which turns empty fields into 0, a value that silently looks like real data.

Delimited numbers: dlmread

dlmread(name, delimiter, r0, c0) reads a delimited file of numbers, starting at row r0 and column c0, counted from zero. That makes skipping a header row easy:

matlab · try it yourself
fid = fopen('scores.csv', 'w');
fprintf(fid, 'student,test1,test2,test3\n101,78,85,91\n102,64,70,\n103,88,92,95\n');
fclose(fid);

S = dlmread('scores.csv', ',', 1, 0)          % skip 1 header row
marks = dlmread('scores.csv', ',', [1 1 3 3])  % range [r0 c0 r1 c1]: just the marks
fprintf('average per test: %s\n', mat2str(mean(marks), 4));
S =

   101    78    85    91
   102    64    70     0
   103    88    92    95

marks =

   78   85   91
   64   70    0
   88   92   95

average per test: [76.67 82.33 62]

Student 102 has no third mark, and dlmread filled it with 0, which drags the average for test 3 down. When a file can have gaps, textscan (gives NaN) is the safer choice. dlmread is still in MATLAB but no longer recommended there; CSV & Delimited Files shows the modern readmatrix too.

Numbers inside strings: sscanf and str2double

Sometimes the numbers come as text you already have in a variable: a line from fgetl, a field from a log message. sscanf is fscanf for strings, and str2double converts whole strings (and cell arrays of strings), returning NaN for anything that isn't a number:

matlab · try it yourself
[vals, count] = sscanf('12.5 kg, 3 boxes', '%f %*s %d');   % %*s skips a word
fprintf('read %d values: %s\n', count, mat2str(vals'));
xy = sscanf('x=3, y=-4', 'x=%d, y=%d')'
v = str2double({'1.5', '2e3', 'abc', ' 7 '})
read 2 values: [12.5 3]
xy =

   3  -4

v =

   1.5000  2000.0000      NaN   7.0000

str2double is the right tool for one number per string: it's fast and never evaluates code. You may also see str2num, which runs the text through eval. It can parse '[1 2; 3 4]', but it will also run any command hidden in the text, so avoid it for data from outside.

Letting MATLAB guess: importdata

importdata looks at the file and separates header text from the numeric block on its own. It's convenient for a quick look, but check what it decided:

matlab · try it yourself
fid = fopen('lab.txt', 'w');
fprintf(fid, 'mass length\n0.10 12.0\n0.20 14.1\n0.30 16.0\n');
fclose(fid);

S = importdata('lab.txt', ' ', 1);     % delimiter ' ', 1 header line
disp(S.colheaders)
disp(S.data)
p = polyfit(S.data(:, 1), S.data(:, 2), 1);
fprintf('length = %.1f * mass + %.2f\n', p(1), p(2));
{
  [1,1] = mass
  [1,2] = length
}
    0.1000   12.0000
    0.2000   14.1000
    0.3000   16.0000
length = 20.0 * mass + 10.03

readmatrix (MATLAB)

Since R2019a, MATLAB's recommended function for numeric files is readmatrix. It detects the delimiter and header lines automatically and turns empty or non-numeric fields into NaN:

matlab
% MATLAB R2019a and later
S = readmatrix('scores.csv')

MATLAB output:

text
S =
   101    78    85    91
   102    64    70   NaN
   103    88    92    95

Octave 11 doesn't have readmatrix; the textscan call with 'Delimiter', ',' and 'HeaderLines', 1 shown above gives the same matrix, with NaN for the missing mark.

Summary

  • Pure numeric text: load. Delimited numbers: dlmread (zero-based offsets; empty fields become 0).
  • fgetl + fscanf(fid, '%f', [ncols Inf])': remember that fscanf fills column by column.
  • textscan handles mixed types, headers, comments and missing values (NaN), returning one cell per column.
  • sscanf/str2double parse numbers inside strings; avoid str2num on untrusted text.
  • importdata guesses the layout; readmatrix is MATLAB's modern one-call reader.

Next: CSV & Delimited Files.

Test yourself

A file has a header line and then 4 numbers per line. After skipping the header, which call reads it into an N-by-4 matrix?

  1. fscanf(fid, '%f', [N 4])
  2. fscanf(fid, '%f', [4 Inf])'
  3. fscanf(fid, '%f', [Inf 4])
  4. fscanf(fid, '%f')

How does dlmread treat an empty field between two commas?

  1. As NaN
  2. As 0
  3. It throws an error
  4. It skips the whole row

What does str2double('abc') return?

  1. 0
  2. An error
  3. NaN
  4. An empty array