MATLAB: Read txt-file with different sizes of columns

matrixtextscan

I'm wish to read, for example the file matrix.txt:
0.15978,0.43759,0.53869,0.0030996
0.41692,0.12178,0.17897,0.65809
0.61909,0.1738,0.98329,0.48912
0.47052,,0.10667,
0.56258,,0.88107,
I try:
fid = fopen('matrix.txt','r');
C = textscan(fid, '%f %f %f %f',Inf,'Delimiter',',');
fclose(fid);
Output:
C =
1×4 cell array
[5×1 double] [5×1 double] [5×1 double] [5×1 double]
C{2}
ans =
0.4376
0.1218
0.1738
0.6584
NaN
But I need C{2} == [4×1 double] (C{4} too).
Someone help me? Thx

Best Answer

I would use cell2mat on the cell array you have, with the NaN values. You can select the individual columns as you need them, and remove the NaN values then, using the isnan operator.
You can remove them in your cell array with this assignment:
Cn = cellfun(@(x)x(~isnan(x)), C, 'Uni',0);
(creating cell array ‘Cn’ to avoid overwriting ‘C’), however that puts empty elements ‘[]’ in place of the NaN values, so you cannot use cell2mat on ‘Cn’.