Search code examples
matlabtextcell-array

Matlab read text file to cell array


I want to read some data from a text file but I don't know how to do this. I know that I can read text files like this

fid=fopen('data.txt');
A = textscan(fid,'%s')

which returns

A =
{
  [1,1] =
  {
    [1,1] = drink
    [2,1] = water
    [3,1] = drink
    [4,1] = eat
    [5,1] = drink
    [6,1] = spoon
    [7,1] = water
    [8,1] = drink
    [9,1] = water
    [10,1] = drink
  }
}

the text file looks like this

drink water drink
eat drink spoon
water drink water drink

But I want to store the data in a cell array like this

A =
{
  [1,1] =
  {
    [1,1] = drink
    [1,2] = water
    [1,3] = drink
  }
  [1,2] =
  {
    [1,1] = eat
    [1,2] = drink
    [1,3] = spoon
  }
  [1,3] =
  {
    [1,1] = water
    [1,2] = drink
    [1,3] = water
    [1,4] = drink
  }
}

How can i solve this?


Solution

  • You can use a combination of importdata and regexp with 'Split' option -

    out = cellfun(@(x) regexp(x,'\s','Split'),importdata(text_filename,'\n'),'un',0).'
    

    Output -

    out{1,1}
    ans = 
        'drink'    'water'    'drink'
    out{1,2}
    ans = 
        'eat'    'drink'    'spoon'
    out{1,3}
    ans = 
        'water'    'drink'    'water'    'drink'