【问题标题】:Determing number of unique data files based on file name根据文件名确定唯一数据文件的数量
【发布时间】:2018-01-20 15:30:31
【问题描述】:

我有一组数据,例如,文件名如下:

data1_1.mat
data1_2.mat
data1_3.mat
data2_1.mat
data2_2.mat
data3_1.mat
data4_1.mat
data4_2.mat

我希望能够确定有多少数据集(即这里有 4 个)以及每个数据集有多少数据子集(即 1 有 3,2 有 2,3 有 1,等等)所以我以后可以在这些上迭代地执行工作。我想弄清楚集合的数量可能是一个结构,并使结构的每个值对应于唯一条目的数量。我不知道该怎么做;有没有dir相关的方法可以使用?

谢谢!

【问题讨论】:

    标签: matlab file dataset load


    【解决方案1】:

    我怀疑是否有一种方法可以完成所有查询,如何在内存中构建数据完全取决于您。但是由于您的文件已经编号,因此我会在数据的数据结构和文件编号之间保持一对一的映射(个人喜好)。

    clc();
    clear();
    
    %   Grab information for all of the mat-files in the PWD
    files = dir('*.mat');
    
    %   Get only the filenames
    fileNames = {files.name};
    
    %   Grab the data set ID and convert the string to a double
    allIDstr = regexp(fileNames(:),'data(\d)','tokens');
    allIDs   = cellfun(@(c) str2double(c{1}),allIDstr);
    
    %   Get the set of unique IDs and a vector that generates it given the original input
    [setIDs,Iuni] = unique(allIDs);
    disp(setIDs(:).');
    
    %   Calculate the number of subsets for each unique ID using Iuni
    nsubsets = diff(Iuni);
    nsubsets = [nsubsets;numel(allIDs) - sum(nsubsets)];
    disp(nsubsets(:).');
    
    %   One way to organize data
    data = cell(numel(setIDs),1);
    for k = 1:numel(setIDs)
        data{k} = cell(nsubsets(k),1);
        for m = 1:nsubsets(k)
            data{k}{m} = load(fileNames{k},'-ascii');
        end
    end
    
    %   Get the data for the second set's second subset
    workdata = data{2}{2};
    

    这个输出:

         1     2     3     4
         3     2     1     2
    >> 
    

    【讨论】:

      【解决方案2】:

      是的,dir、containers.Map 和字符串操作的组合很容易实现。

      示例代码

      dirPath = 'folder/*.mat';
      files = dir(dirPath);
      
      % Store all file information in a dictionary
      dataSet = containers.Map('KeyType', 'double', 'ValueType', 'any');
      
      for i = 1:length(files)
          parts = strsplit(erase(files(i).name, "data"), {'_', '.'});
      
          % Main set index
          fID = str2double(parts{1});
      
          % Add this file to set and increment counter of dictionary
          if dataSet.isKey(fID)
              setInfo = dataSet(fID);
              setInfo.count = setInfo.count + 1;
              setInfo.files{end+1} = files(i).name;
          else
              setInfo.count = 1;
              setInfo.files = {files(i).name};
          end
          dataSet(fID) = setInfo;
      end
      
      disp(dataSet)
      

      然后,可以找到集合为dataSet.keys(),通过访问key可以找到每个集合中的文件,例如:

      >> dataSet(1)
      ans = 
      
        struct with fields:
      
          count: 2
          files: {'data1_1.mat'  'data1_2.mat'}
      

      【讨论】:

        猜你喜欢
        • 2011-04-27
        • 2015-08-05
        • 2020-10-14
        • 1970-01-01
        • 2023-02-22
        • 2020-01-05
        • 2022-01-19
        • 2021-10-07
        • 2021-03-13
        相关资源
        最近更新 更多