Eugenio
Eugenio

Reputation: 3445

Matlab doesn't recognize empty values at the end of a CSV file line

I am reading with Matlab a CSV file; the file can contain empty values which I want to convert into 0

FID=fopen('/file.txt','r');
text_line = fgetl(FID);
C = textscan(text_line,'%d','delimiter',',','EmptyValue', 0);

If the empty value is in the middle of the line, e.g.

5,,6

everything works fine and the variable C gets

5 0 6

as values. If the empty value is at the end, e.g.

5,6,

Matlab doesn't recognize it and the C variable gets

5 6

as values, instead of

5 6 0

EDIT After Dennis answer: I don't understand why the number of elements expected is needed, I give the separator, shouldn't it be enough? Anyway I tried and the result is different: with %d%d%d I get

C = 

    [5]    [0x1 int32]     [6]    

with %d everything is in the first element so

C{1}

ans =

           5
           0
           6

This code snippet is part of a procedure which import a very big CSV matrix into a matlab sparse matrix (see my post Handling a very big and sparse matrix in Matlab) and I guess (not tried yet) that the first approach is faster.

Anyway, my values are actually >290k per line so I guess it wouldn't be a feasible option to specify all the %d

Upvotes: 0

Views: 300

Answers (1)

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

Judging from this answer on matlab central you need to tell Matlab how many values you expect.

In your case I would expect this to translate to:

FID=fopen('/file.txt','r');
text_line = fgetl(FID);
C = textscan(text_line,'%d%d%d','delimiter',',','EmptyValue', 0);

Upvotes: 4

Related Questions