Search code examples
matlabcellfopen

Matlab: Put each line of a text file in a separate array


I have a file like the following

 10158 18227 2055 24478 25532 
 12936 14953 17522 17616 20898 24993 24996 
 26375 27950 32700 33099 33496 3663 
 ...

I would like to put each line in an array in order to access elements of each line separately. I used cell arrays but it seems to create a 1 by 1 array for each cell element:

fid=fopen(filename)
nlines = fskipl(fid, Inf)
frewind(fid);
cells = cell(nlines, 1);
for ii = 1:nlines
    cells{ii} = fscanf(fid, '%s', 1);
end
fclose(fid);

when I access cells{ii} I get all values in the same element and I can't access the list values


Solution

  • I think that fscanf(fid, '%s', 1); is telling matlab to read the line a single string. You will still have to convert it to an array of numbers:

    for ii = 1:nlines
        cells{ii} = str2num(fscanf(fid, '%s', 1));
    end