MATLAB: How to read data from file (different line lengths)

formattingstructurestext filetextscan

Hi,
Lets say I printed to file data about some video clip. The data is for each frame in the clip, line by line.
For each frame I printed the frame number, the camera code and points that I recognized in this frame (pairs of X and Y) and there is no limit to the number of points (all the data is in floats).
example:
The first frame can be something like this: 1 1 2 5 3 6 88 0
and the second frame can be: 2 6
The first line indicates that in frame number #1 we have 3 points: (2,5)(3,6)(88,0) and the camera code is 1.
The second line indicate that in frame number #2 there are no points at all and the camera code is 6.
What is the most convenient way to read this file?
I read about textread but the format in this way should be very strict (fixed number of points…).
I would like to get a data structure that will store all the data in reasonable and convenient way.
EDIT: I need division between the data, i.e. for the first line: 'frame'= 1, 'camType'=1, 'points' = struct of the points (2,5),(3,6),(88,0)
Thanks.

Best Answer

This is how I'd do it:
function data = readfile(filepath)
data = struct('frame', [], 'camera', [], 'points', []);
fid = fopen('yourfile.txt', 'rt'); %open as text. (Takes care of newline conversions)
cleanupobj = onCleanup(@() fclose(fid)); %close file at end of function or if error
linecount = 1;
while ~feof(fid)
values = str2double(strsplit(fgetl(fid))); %str2double is a lot safer than str2num
data(linecount).frame = values(1);
data(linecount).camera = values(2);
data(linecount).points = reshape(values(3:end), 2, []).';
linecount = linecount + 1;
end
end