Search code examples
matlabtext-processingcell-array

Reading data file with rows of variable sizes


I have a data file containing rows of variable sizes:

16 54 1 -3 5
15 5
1 9 10 5

How can I load it into a cell array data so that

data{1} = [16 54 1 -3 5]; 
data{2} = [15 5]; 
data{3} = [1 9 10 5];

?


Solution

  • Let data.txt contains

    16 54 1 -3 5
    15 5
    1 9 10 5
    

    You can read it into a cell array data with the following:

    fid = fopen('datatest.txt');
    allData = textscan(fid,'%s','Delimiter','\n');
    data = cellfun(@str2num, allData{1}, 'UniformOutput', false);
    fclose(fid);
    
    >> data = 
    
    ans =    
    
    [1x5 double]
    [1x2 double]
    [1x4 double]
    
    >> data{1}
    
    ans =
    
        16    54     1    -3     5