【问题标题】:How to load a text file and store into data structure如何加载文本文件并存储到数据结构中
【发布时间】:2014-04-09 16:25:05
【问题描述】:

我有一个“文本”文件,其内容如下:

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 中加载此文件并将图像名称存储到“名称”变量中,并将 240 个值存储到“直方图”变量中?

【问题讨论】:

    标签: matlab text text-parsing


    【解决方案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
    

    【讨论】:

    • 但现在“名称”包含图像名称,然后也包含 240 个实际值
    • @VarunDas 我不确定我是否遵循您的评论。但我做了一个可能与此相关的更正
    【解决方案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
    

    【讨论】:

    • repmat 命令将 240 '%f' 放入格式字符串中。然后'CollectOutput' 选项将所有相同的数据类型放在一个单元格中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 2013-03-27
    • 2022-11-16
    • 1970-01-01
    相关资源
    最近更新 更多