Reading text files in Matlab

kaz - February 13, 2012 Coded in Matlab

Using file io functions in Matlab is a bit of confusion due to the variety and the issue of vectorisation.

In the following snippet data is read back using:

fscanf : creates a vector row by row

textread (or its replacement textscan): creates matrix

importdata: creates matrix

load: creates matrix

I normally use 'textread' followed by my own vectorisation. textread has rich features such as skipping header, skipping columns ...etc.

clear all;

% create test file
data = [1 5 2 4 3 3 4 2 5 1];
filename = 'test_file.txt';
fid = fopen(filename, 'w');
fprintf(fid, '%d %d\n', data);

% (1) read file using fscanf 
fid = fopen(filename, 'r'); 
y1 = fscanf(fid, '%d\n'); %interleaves columns

% (2) read file using textread (or textscan)
[ya,yb] = textread(filename,'%d%d');
y2 = [ya yb];

% (3) read file using importdata 
y3 = importdata(filename);

% (4) read file using load 
y4 = load(filename);

disp('    original vector data')
disp('    file content using fprintf')
disp('    vector created by fscanf')
disp('     matrix created by:')
disp('     textread   importdata    load')
disp([y2 y3 y4])