如何加载文本文件并存储到数据结构中

时间:2014-03-06 19:53:57

标签: matlab text text-parsing

我有一个'text'文件,内容如下:

012abc3cb7503bddef3ff59e0e52fd79.jpg 160.073318 18.588472 14.246923 8.054444 6.600504 6.261390 5.838249 4.447019 3.639888 3.357715 2.996645 2.910991 2.574769 2.527163 2.343448 2.264113 2.176161 2.088773 1.915582 1.902159 1.836033 1.725432 1.667595 1.633245 1.557424 1.542059 1.434280 1.430181 1.321047 1.302652 1.272890 1.261313 1.188892 1.138115 1.114376 1.070352 1.044311 1.025954 0.993622 0.988920 0.969866 0.933977 0.931669 0.913624 0.882856 0.876036 0.840088 0.822686 0.814072 0.787075 0.781157 0.778171 0.763771 0.748851 0.740975 0.708208 0.691589 0.688566 0.664124 0.659779 0.644820 0.623200 0.614799 0.607180 0.590615 0.578751 0.57...........

每行代表一个图像(实例),第一列是图像名称,其余240列是图像的特征向量。

如何在MATLAB中加载此文件并将图像名称存储到“names”变量中,将240值存储到“histogram”变量中?

2 个答案:

答案 0 :(得分:2)

您可以使用textscanrepmat来完成此操作,这样您就可以避免从字符串转换:

Nfeatures = 240;
fid = fopen('text.txt');
format = ['%s ' repmat('%f', [1 Nfeatures])];
imageFeatureCell = textscan(fid, format, 'CollectOutput', true);
fclose(fid);

对包含7行的文件进行测试:

>> fileData
fileData = 
    {7x1 cell}    [7x240 double]

进入所需的变量:

names = fileData{1};      % names{1} contains first file name, etc.
histogram = fileData{2};  % histogram(1,:) contains first file's features

答案 1 :(得分:1)

str = textread('tmp.txt','%s');
str = reshape(str,241,[]).';
names = str(:,1); %'// cell array of strings with image names
histogram = str2double(str(:,2:end)); %// each row refers to an image