File io 根据条件将文本文件内容读入矩阵
我有以下格式的文本文件:File io 根据条件将文本文件内容读入矩阵,file-io,octave,File Io,Octave,我有以下格式的文本文件: Food Fruits1 [heading] Apple [value] Mango [value] Orange [value] Veg1 [heading] Potato [value] Lettuce [value] ---------------------------------------------------------------------- Item | Frui
Food
Fruits1 [heading]
Apple [value]
Mango [value]
Orange [value]
Veg1 [heading]
Potato [value]
Lettuce [value]
----------------------------------------------------------------------
Item | Fruits1 | Apple | Mango | Orange | Veg1 | Potato | Lettuce
----------------------------------------------------------------------
| | | | | | |
----------------------------------------------------------------------
我想将其作为以下格式的矩阵加载到倍频程中:
Food
Fruits1 [heading]
Apple [value]
Mango [value]
Orange [value]
Veg1 [heading]
Potato [value]
Lettuce [value]
----------------------------------------------------------------------
Item | Fruits1 | Apple | Mango | Orange | Veg1 | Potato | Lettuce
----------------------------------------------------------------------
| | | | | | |
----------------------------------------------------------------------
因此,我需要一个大小为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;
fid=fopen('food.txt','r');
num=1;
如果(fid<0)
printf('错误:无法打开文件\n')
其他的
而~feof(fid),
直线=fgetl(fid);
arr=[line;];
num=num+1;
结束;
fclose(fid)
结束;
由于字符串的长度不同,因此无法创建矩阵。只能把它放进牢房里。但我推荐一个结构化的列表
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
这不是小事。“你应该向我们展示你所做的努力,激励我们做得更好。”WayWewalk Point指出!我补充了我迄今为止所做的工作。