saloua
saloua

Reputation: 2493

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

Upvotes: 0

Views: 808

Answers (2)

Dan
Dan

Reputation: 45752

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

Upvotes: 1

Eitan T
Eitan T

Reputation: 32930

A shorter solution would be reading the file with textscan:

fid = fopen(filename, 'r');
C = cellfun(@str2num, textscan(fid, '%s', 'delimiter', ''), 'Uniform', false);
fclose(fid);

The resulting cell array C is what you're looking for.

Upvotes: 2

Related Questions