TExcelTAD
Home › MATLAB / Octave › CSV & Delimited Files

CSV & Delimited Files

CSV (comma-separated values) is the most common format for tabular data: every spreadsheet program, database and data logger can write it. Each line is a row, a delimiter separates the fields, and the first line usually holds column names. The format looks trivial, but real files bring headers, text columns, missing values, quoted fields that contain commas, and regional variants with semicolons and decimal commas. This lesson shows how to handle each of them.

Task Both MATLAB and Octave Modern MATLAB only
Write a numeric matrix dlmwrite(name, M, 'precision', ...), csvwrite(name, M) writematrix(M, name)
Read a numeric matrix dlmread(name, ',', r0, c0), csvread(name, r0, c0) readmatrix(name)
Write header + data, text columns fprintf to the file writetable(T, name), writecell(C, name)
Read mixed text and numbers textscan(fid, fmt, 'Delimiter', ',') readtable(name), readcell(name)

Note: each example creates its own CSV file first, then reads it back.

Writing numbers

csvwrite(name, M) writes a matrix with commas and newlines. It is short, but it gives you no control over the number format, and that format differs: MATLAB's csvwrite keeps only 5 significant digits (so 3.14159265 becomes 3.1416), while Octave writes full precision. dlmwrite with an explicit 'precision' gives the same file in both, so prefer it:

matlab · try it yourself
M = [1 2.5; 1/3 1000000; pi -0.125];
dlmwrite('values.csv', M, 'precision', '%.4f');    % printf-style format
fprintf('%s', fileread('values.csv'));
dlmwrite('values_g.csv', M, 'precision', 6);       % a number = significant digits
fprintf('%s', fileread('values_g.csv'));
1.0000,2.5000
0.3333,1000000.0000
3.1416,-0.1250
1,2.5
0.333333,1e+06
3.14159,-0.125

Other dlmwrite options: 'delimiter', ';' or 'delimiter', '\t' for other separators, '-append' to add rows to an existing file, 'newline', 'pc' for Windows line endings, and 'roffset'/'coffset' to leave empty rows or columns first.

A header row, then data

Spreadsheet users expect column names. Write the header line with fprintf, then append the numbers with dlmwrite(..., '-append'). To read the file back, skip the header with a row offset of 1 (offsets count from zero):

matlab · try it yourself
hdr = {'hour', 'temp_c', 'wind_ms'};
data = [6 11.2 3.4; 12 17.8 5.1; 18 15.1 4.0];

fid = fopen('weather.csv', 'w');
fprintf(fid, '%s\n', strjoin(hdr, ','));
fclose(fid);
dlmwrite('weather.csv', data, '-append', 'precision', '%g');
fprintf('%s', fileread('weather.csv'));

W = csvread('weather.csv', 1, 0);              % same as dlmread(name, ',', 1, 0)
fprintf('warmest at %d:00 (%.1f C)\n', W(W(:, 2) == max(W(:, 2)), 1), max(W(:, 2)));
hour,temp_c,wind_ms
6,11.2,3.4
12,17.8,5.1
18,15.1,4
warmest at 12:00 (17.8 C)

To read the header back as names, take the first line with fgetl and split it: names = strsplit(fgetl(fid), ',').

Text columns: writing with fprintf

dlmwrite and csvwrite handle numbers only. For mixed rows, write each line with fprintf, looping over the records. Here the data lives in a struct array:

matlab · try it yourself
s = struct('name', {'Ada', 'Boris', 'Chen'}, 'dept', {'R&D', 'Sales', 'R&D'}, ...
           'salary', {5200, 4100, 4800});
fid = fopen('staff.csv', 'w');
fprintf(fid, 'name,dept,salary\n');
for k = 1:numel(s)
    fprintf(fid, '%s,%s,%d\n', s(k).name, s(k).dept, s(k).salary);
end
fclose(fid);
fprintf('%s', fileread('staff.csv'));
name,dept,salary
Ada,R&D,5200
Boris,Sales,4100
Chen,R&D,4800

Text columns: reading with textscan

textscan reads such a file in one call. %s reads text, %f numbers; 'Delimiter', ',' makes the comma the only separator (so a space inside a field doesn't split it), and 'HeaderLines', 1 skips the column names:

matlab · try it yourself
fid = fopen('staff.csv', 'w');
fprintf(fid, 'name,dept,salary\nAda,R&D,5200\nBoris,Sales,4100\nChen,R&D,4800\nDana,Sales,\n');
fclose(fid);

fid = fopen('staff.csv', 'r');
header = strsplit(fgetl(fid), ',');               % read the header first
C = textscan(fid, '%s %s %f', 'Delimiter', ',');
fclose(fid);
[name, dept, salary] = C{:};
fprintf('columns: %s\n', strjoin(header, ' | '));
fprintf('%d rows; missing salaries: %d\n', numel(name), sum(isnan(salary)));
for d = unique(dept)'
    in = strcmp(dept, d{1});
    fprintf('%-6s mean salary %.0f\n', d{1}, mean(salary(in), 'omitnan'));
end
columns: name | dept | salary
4 rows; missing salaries: 1
R&D    mean salary 5000
Sales  mean salary 4100

unique(dept)' gives the distinct department names as a row, so the for loop takes one name per pass (as a 1-by-1 cell, hence d{1}). The missing salary became NaN and 'omitnan' left it out of the mean.

Quoted fields

When a field itself contains a comma, CSV writers put it in double quotes: "Smith, Ann". Splitting such a line at every comma breaks the field in two. textscan's %q format reads a possibly quoted field and removes the quotes:

matlab · try it yourself
fid = fopen('orders.csv', 'w');
fprintf(fid, 'customer,city,amount\n"Smith, Ann",Oslo,12.5\nBo Lee,"New York",7\n');
fclose(fid);

fid = fopen('orders.csv', 'r');
C = textscan(fid, '%q %q %f', 'Delimiter', ',', 'HeaderLines', 1);
fclose(fid);
for k = 1:numel(C{1})
    fprintf('%-12s %-9s %5.2f\n', C{1}{k}, C{2}{k}, C{3}(k));
end
Smith, Ann   Oslo      12.50
Bo Lee       New York   7.00

When writing text that might contain the delimiter, wrap it in quotes yourself: fprintf(fid, '"%s",%d\n', name, n).

Semicolons and decimal commas

In many European locales, spreadsheets use the comma as the decimal separator and therefore the semicolon as the field delimiter: pear;0,90. Read such numbers as text, swap the decimal comma for a point, then convert:

matlab · try it yourself
fid = fopen('prices.csv', 'w');
fprintf(fid, 'item;price\napple;1,25\npear;0,90\nplum;2,05\n');
fclose(fid);

fid = fopen('prices.csv', 'r');
C = textscan(fid, '%s %s', 'Delimiter', ';', 'HeaderLines', 1);
fclose(fid);
price = str2double(strrep(C{2}, ',', '.'));
fprintf('%s costs %.2f\n', C{1}{1}, price(1));
fprintf('total %.2f for %d items\n', sum(price), numel(price));
apple costs 1.25
total 4.20 for 3 items

Tip: when you split CSV lines yourself, remember that strsplit merges consecutive delimiters by default, so strsplit('a,,c', ',') gives two fields, not three. Use strsplit(line, ',', 'CollapseDelimiters', false) to keep empty fields.

readmatrix, readtable and friends (MATLAB)

Modern MATLAB reads and writes CSV with functions that detect delimiters, headers and column types automatically:

matlab
% MATLAB R2019a and later
writematrix([1 2.5; 3 4], 'm.csv');
M = readmatrix('m.csv')
T = readtable('staff.csv')        % the staff file from above, with the missing salary

MATLAB output:

text
M =
    1.0000    2.5000
    3.0000    4.0000

T =
  4×3 table
      name         dept      salary
    _________    _________    ______
    {'Ada'  }    {'R&D'  }     5200 
    {'Boris'}    {'Sales'}     4100 
    {'Chen' }    {'R&D'  }     4800 
    {'Dana' }    {'Sales'}      NaN 

readtable uses the header line as variable names and returns a table; writetable(T, 'out.csv') writes one back with its header. readcell returns every field as a cell, and detectImportOptions lets you fine-tune what readtable guesses. Octave 11 has none of these functions (the io package adds csv2cell); the textscan code above does the same job in both programs.

Summary

  • Write numbers with dlmwrite(name, M, 'precision', fmt) for identical output everywhere; csvwrite's precision differs between MATLAB and Octave.
  • Write a header line with fprintf, then dlmwrite(..., '-append'); read with a row offset of 1 (zero-based).
  • Mixed columns: write rows with fprintf, read them with textscan(fid, '%s %f ...', 'Delimiter', ','); %q handles quoted fields.
  • Semicolon files with decimal commas: read as text, strrep(',', '.'), str2double.
  • readmatrix/readtable/writetable are MATLAB's modern one-liners.

Next: MAT-Files: save & load. Learn more: pandas read_csv does the same in Python.

Test yourself

Which call reads a CSV of numbers while skipping its single header row?

  1. csvread('f.csv', 1, 0)
  2. csvread('f.csv', 0, 1)
  3. csvread('f.csv', 2, 1)
  4. csvread('f.csv', 'header')

Which textscan format reads a field like "Smith, Ann" as a single value?

  1. %s
  2. %c
  3. %q
  4. %f

Why use dlmwrite(name, M, 'precision', '%.4f') instead of csvwrite(name, M)?

  1. csvwrite can't write commas
  2. It controls the number format, so the file is the same in MATLAB and Octave
  3. dlmwrite is faster
  4. csvwrite only writes integers