smilingbuddha
smilingbuddha

Reputation: 14670

Reading file line by line in matlab

I have an input file to a MATLAB code, which lists indices of neighbouring vertices in a mesh. For a vertex with the same rank as the line number of the file, I list the neighbouring vertex indices on that same line.
e.g.

45, 56, 22
44, 12
12, 23,56,76

I want to read in this file into my code as a cell-array. as follows.

NBR = { {45,56,22}, {44,12}, {12,23,56,76} }

Is there any MATLAB function to accomplish this?

Upvotes: 2

Views: 1897

Answers (2)

timgeb
timgeb

Reputation: 78780

New answer:

I finally found a somewhat nice solution. Actually, importdata can be helpful here, thanks @Divakar.

>> C = importdata('file','')
C = 
    '45, 56, 22'
    '44, 12'
    '12, 23,56,76'
>> C = cellfun(@str2num, C, 'UniformOutput', 0)
C = 
    [1x3 double]
    [1x2 double]
    [1x4 double]
>> C = cellfun(@(x) mat2cell(x, [1], ones(size(x,2),1)), C, 'UniformOutput', 0)'
C = 
    {1x3 cell}    {1x2 cell}    {1x4 cell}
>> NBR = { {45,56,22}, {44,12}, {12,23,56,76} };
>> isequal(NBR,C)
ans =
     1

Old answer:

Unfortunately importdata seems to be too limited for this task and I did not find a good way of reading the whole file with textscan and then applying some cellfuns either. csvread has the problem of inserting 0 where there should be NaN values, so that will not work for datasets which actually contain zeros.

So the old-fashioned way would look like this:

fid = fopen('file');
ind = 1;
line = fgetl(fid); % #get first line

while line ~= -1; % #read until end of file
    cont = cellfun(@str2num, strsplit(line, ','));
    cont = mat2cell(cont, [1], ones(size(cont,2),1));
    C{ind} = cont;
    line = fgetl(fid);
    ind = ind + 1;
end

fclose(fid);

Demo, where my script is saved as readin.m:

>> readin
>> C
C = 
    {1x3 cell}    {1x2 cell}    {1x4 cell}
>> C{1}
ans = 
    [45]    [56]    [22]
>> C{2}
ans = 
    [44]    [12]
>> C{3}
ans = 
    [12]    [23]    [56]    [76]
>> NBR = {{45,56,22}, {44,12}, {12,23,56,76}};
>> isequal(NBR,C)
ans =
     1

Upvotes: 2

Alyafey
Alyafey

Reputation: 1453

You can use fgets to read from file line by line in matlab

fid = fopen('yourfile');

tline = fgets(fid);
while ischar(tline)
    disp(tline)
    tline = fgets(fid);
end

fclose(fid);

Upvotes: 1

Related Questions