Matlab将文本文件读取到单元格数组

时间:2014-10-29 20:50:15

标签: matlab text cell-array

我想从文本文件中读取一些数据,但我不知道如何做到这一点。 我知道我可以阅读像这样的文本文件

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

返回

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
  }
}

文本文件如下所示

drink water drink
eat drink spoon
water drink water drink

但我想将数据存储在像这样的单元格数组中

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
  }
}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您可以将importdataregexp'Split'选项结合使用 -

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

输出 -

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