Search code examples
arraysmatlabcsvcellcell-array

MATLAB: How to populate a cell array from a CSV file?


There are many questions on topics of text files and cell arrays but none is related to the problem that I am facing. I have a text file with numeric data like this:

1,2,3,4,5
6,7,8
9,10,11,12,13,14,15

I want this text to be put into a cell array with dimensions

[1X5]
[1X3]
[1X7]

I have tried csvread but it makes a matrix and all void elements are set to 0, which is not what I want. I'd be thankful for some help, please.


Solution

  • You can try an importdata based approach, assuming data.txt to be your input text-file.

    data1 = importdata('data.txt','')
    

    You would get -

    data1 = 
        '1,2,3,4,5'
        '6,7,8'
        '9,10,11,12,13,14,15'
    

    and then -

    out = cellfun(@(x) str2num(char(strsplit(x,',')))',data1,'uni',0)
    

    You would get your desired output -

    out = 
        [1x5 double]
        [1x3 double]
        [1x7 double]
    

    You can display their values with celldisp(out) -

    out{1} =
     1     2     3     4     5
    out{2} =
     6     7     8
    out{3} =
     9    10    11    12    13    14    15