TExcelTAD
Home › MATLAB / Octave › Importing & Exporting Data

Importing & Exporting Data

The previous lessons each covered one kind of file. Real projects mix them: data arrives as CSV from a logger, JSON from a web service, a spreadsheet from a colleague; results leave as a report, a MAT-file and a figure. This lesson is the map: which function reads and writes which format, what works in both MATLAB and Octave, and how to check that an export really contains what you meant.

Which function for which format?

Format Read Write Notes
Plain text fileread, fgetl, textscan fprintf Text files
Numbers in text load, dlmread, fscanf dlmwrite, save -ascii Reading numeric data
CSV / delimited textscan, dlmread, csvread fprintf, dlmwrite CSV files
MAT-file load save(..., '-v7') MAT-files
JSON jsondecode(fileread(f)) fprintf(fid, '%s', jsonencode(x)) JSON Data; both programs
Images imread, imfinfo imwrite Images & Colormaps
Audio (WAV, FLAC, OGG) audioread, audioinfo audiowrite Both programs
Raw binary fread fwrite Exact bytes, any numeric type
Excel .xlsx readtable, readmatrix, readcell writetable, writematrix MATLAB; Octave needs the io package
XML readstruct, xmlread writestruct, xmlwrite MATLAB only
HDF5, NetCDF h5read, ncread h5write, ncwrite MATLAB; Octave packages exist
Web APIs webread webwrite Both programs (network needed)
Unknown layout importdata, the Import Tool (uiimport) MATLAB's Import Tool can generate the reading code for you

A good habit for any new data source: open it interactively once (MATLAB's Import Tool, or fileread and a look at the first lines), decide on the reading code, then put that code in a script so the import is repeatable.

One data set, three exports

Suppose an analysis produced a small results table, stored as a struct array. Different audiences want different formats: a CSV for the spreadsheet users, JSON for a web dashboard, and a MAT-file to continue working in MATLAB later:

matlab · try it yourself
results = struct('site', {'North', 'East', 'South'}, ...
                 'samples', {120, 95, 143}, ...
                 'mean_ph', {6.84, 7.12, 6.97});

% 1) CSV for spreadsheets
fid = fopen('results.csv', 'w');
fprintf(fid, 'site,samples,mean_ph\n');
for r = results
    fprintf(fid, '%s,%d,%.2f\n', r.site, r.samples, r.mean_ph);
end
fclose(fid);

% 2) JSON for a web page
fid = fopen('results.json', 'w');
fprintf(fid, '%s', jsonencode(results));
fclose(fid);

% 3) MAT-file for later work
save('results.mat', 'results', '-v7');

fprintf('%s', fileread('results.csv'));
disp(fileread('results.json'))
site,samples,mean_ph
North,120,6.84
East,95,7.12
South,143,6.97
[{"site":"North","samples":120,"mean_ph":6.84},{"site":"East","samples":95,"mean_ph":7.12},{"site":"South","samples":143,"mean_ph":6.97}]

for r = results loops over the elements of a struct array (it iterates over columns, and a 1-by-3 struct array has three). jsonencode turns a struct array into a JSON array of objects, using the field names as keys.

Reading them back and checking

An export isn't done until you've read it back. Each format returns the data in a slightly different shape, so compare the parts that matter, with a tolerance for numbers that were rounded on the way out:

matlab · try it yourself
results = struct('site', {'North', 'East', 'South'}, ...
                 'samples', {120, 95, 143}, 'mean_ph', {6.84, 7.12, 6.97});
fid = fopen('results.csv', 'w');
fprintf(fid, 'site,samples,mean_ph\n');
for r = results, fprintf(fid, '%s,%d,%.2f\n', r.site, r.samples, r.mean_ph); end
fclose(fid);
fid = fopen('results.json', 'w');  fprintf(fid, '%s', jsonencode(results));  fclose(fid);
save('results.mat', 'results', '-v7');

% CSV -> cell array of columns
fid = fopen('results.csv', 'r');
C = textscan(fid, '%s %f %f', 'Delimiter', ',', 'HeaderLines', 1);
fclose(fid);
% JSON -> struct array (a column, 3-by-1)
J = jsondecode(fileread('results.json'));
% MAT -> the original variable
M = load('results.mat');

ph = [results.mean_ph];
fprintf('CSV : sites match %d, pH within 0.005: %d\n', isequal(C{1}', {results.site}), all(abs(C{3}' - ph) < 0.005));
fprintf('JSON: size %s, sites match %d, pH match %d\n', mat2str(size(J)), ...
        isequal({J.site}, {results.site}), isequal([J.mean_ph], ph));
fprintf('MAT : identical %d\n', isequal(M.results, results));
CSV : sites match 1, pH within 0.005: 1
JSON: size [3 1], sites match 1, pH match 1
MAT : identical 1

Three different stories. The MAT-file returns the variable exactly. JSON keeps names and full-precision numbers, but jsondecode returns the array of objects as a 3-by-1 column. CSV turns everything into text, so the types and the shape have to be rebuilt by the reading code, and numbers come back only as precise as you wrote them (%.2f here). Even when the text is exact, don't test parsed numbers with ==: Octave's textscan can be off in the last bit (the text 7.12 can come back as the double just below 7.12), while str2double and sscanf are exact. A tolerance, as above, works everywhere.

Raw binary files

Instruments and other programs sometimes exchange raw binary data: just the bytes of the numbers, no header, no separators. fwrite(fid, data, precision) writes values as a given type and fread(fid, n, precision) reads them; the precision string must match on both sides. A 'source=>target' precision such as 'uint16=>uint16' keeps the read values in that class instead of converting them to double:

matlab · try it yourself
fid = fopen('packet.bin', 'w');
fwrite(fid, uint16([1 256 65535]), 'uint16');    % 3 values x 2 bytes
fwrite(fid, [pi -1.5], 'double');                % 2 values x 8 bytes
fclose(fid);

fid = fopen('packet.bin', 'r');
counts = fread(fid, 3, 'uint16=>uint16')';
values = fread(fid, 2, 'double')';
fseek(fid, 0, 'eof');
nbytes = ftell(fid);                             % position at the end = file size
fclose(fid);
fprintf('counts %s (%s), values %s, %d bytes\n', mat2str(counts), class(counts), mat2str(values, 6), nbytes);
counts [1 256 65535] (uint16), values [3.14159 -1.5], 22 bytes

Binary files are compact and fast, but they carry no description: the reader must know the exact layout, and the byte order (endianness). fopen(name, 'r', 'ieee-be') reads big-endian data, which some older instruments and network formats use.

Audio files

audiowrite(file, y, fs) saves samples y (values between −1 and 1, one column per channel) at sample rate fs, and audioread returns them. WAV files store 16-bit integers by default, so the values come back rounded to the nearest of 65536 levels:

matlab · try it yourself
fs = 8000;                                   % samples per second
t = (0:fs-1)' / fs;                          % one second
y = 0.5 * sin(2*pi*440*t);                   % concert-pitch A
audiowrite('tone.wav', y, fs);

[z, fs_read] = audioread('tone.wav');
info = audioinfo('tone.wav');
fprintf('%d samples at %d Hz, %d channel(s), %d bits\n', numel(z), fs_read, info.NumChannels, info.BitsPerSample);
fprintf('rounding error below 1/32768: %d\n', max(abs(z - y)) <= 1/32768);
8000 samples at 8000 Hz, 1 channel(s), 16 bits
rounding error below 1/32768: 1

Spreadsheets and other MATLAB-only readers

Excel files are the one format that people constantly send around and that the two programs handle differently. In MATLAB, readtable reads .xlsx like a CSV, with a 'Sheet' and 'Range' option:

matlab
% MATLAB
T = readtable('budget.xlsx', 'Sheet', 'Q1', 'Range', 'A1:C4')
writetable(T, 'budget_copy.xlsx', 'Sheet', 'Backup')

MATLAB output (for a sheet with three rows of data):

text
T =
  3×3 table
      item       planned    actual
    _________    _______    ______
    {'Rent' }     1200       1200 
    {'Food' }      450        512 
    {'Other'}      300        245 

In Octave, install and load the io package (pkg install -forge io, then pkg load io), which provides xlsread, xlswrite and csv2cell. When you control the pipeline, the simplest portable route is to ask for (or save from the spreadsheet) a CSV export and read it with textscan.

The older xlsread and xlswrite still exist in MATLAB but are no longer recommended. Similarly, readstruct/writestruct (MATLAB R2020b+) read and write XML and JSON straight into structs; Octave has no XML reader, so XML data is best converted to JSON or CSV first.

Summary

  • Pick the format for the reader: CSV for spreadsheets, JSON for web tools, MAT-files (-v7) for MATLAB/Octave/Python, raw binary only with a documented layout.
  • jsonencode/jsondecode, imread/imwrite, audioread/audiowrite, fread/fwrite and the text/CSV functions work in both programs; Excel, XML, HDF5 and readtable are MATLAB features or need Octave packages.
  • Always read an export back and compare it with the original, with a tolerance for rounded numbers.

This completes the Files & Data I/O section. Next: Linear Algebra. Learn more: A Data Analysis Workflow puts importing, cleaning and exporting together.

Test yourself

Which export keeps every variable's type and value exactly, for later work in MATLAB or Octave?

  1. CSV
  2. JSON
  3. A MAT-file saved with -v7
  4. A PNG image

What does jsondecode return for a JSON array of three objects with the same keys?

  1. A 1-by-3 cell array
  2. A 3-by-1 struct array
  3. A table
  4. A character vector

What must the reader of a raw binary file know?

  1. Nothing; the file describes itself
  2. The exact layout: types, counts and byte order
  3. Only the file name
  4. The delimiter