根据条件将文本文件内容读入矩阵

时间:2015-07-12 14:21:25

标签: file-io octave

我有这种格式的文本文件:

Food
Fruits1     [heading]
    Apple    [value]
    Mango    [value]
    Orange   [value]
Veg1        [heading]
    Potato   [value]
    Lettuce  [value]

我想将此格式加载到 Octave 中作为此格式的矩阵:

----------------------------------------------------------------------
Item | Fruits1 | Apple | Mango | Orange | Veg1 | Potato | Lettuce
----------------------------------------------------------------------
     |         |       |       |        |      |        |         
----------------------------------------------------------------------

因此,我需要一个size = 2x(n + m + 1)的矩阵;其中n = [标题]的数量,m = [值]的数量。

如何使用 fgetl 从文本文件中读取每一行并存储到满足上述条件的矩阵中?有更好的想法吗?

谢谢!

编辑:代码: -

fid = fopen('food.txt','r');
num = 1;
  if (fid < 0) 
    printf('Error:could not open file\n')
  else
    while ~feof(fid),
    line = fgetl(fid);
    arr=[line;];     
    num=num+1;
    end;
        fclose(fid)
  end; 

1 个答案:

答案 0 :(得分:0)

无法使用矩阵,因为您的字符串长度不同。它只能将它放入一个细胞中。但我会推荐一个结构化的清单。

fid = fopen('list.txt');

while 1
  tmp = fgetl(fid);
  if ~ischar(tmp)
    % end of file
    break
  end

  if strcmp(deblank(tmp), 'Food')
    # this can't be empty
    listObj.('item') = 'Food';
  else
    tmp = cell2mat(regexp(deblank(tmp),'(\w+)','tokens'));
    if strcmp(tmp{1,2}, 'heading')
      head = tmp{1,1};
    else
      listObj.(head).(tmp{1,1}) = str2double(tmp{1,2});
    end
  end
end

您可以更好地访问它。

>> stackoverflow
>> listObj
listObj =

  scalar structure containing the fields:

    item = Food
    Fruits1 =

      scalar structure containing the fields:

        Apple =                    3
        Mango =                    4
        Orange =                    1

    Veg1 =

      scalar structure containing the fields:

        Potato =                    8
        Lettuce =                    0


>> listObj.Fruits1.Apple
ans =                    3
>> listObj.Veg1.Lettuce
ans =                    0
>>

但请注意您的输入文件,必须严格格式化。我的示例文件看起来像这样

Food
Fruits1     [heading]
    Apple    3
    Mango    4
    Orange   1
Veg1        [heading]
    Potato   8
    Lettuce  0