【问题标题】:Loading text file in MATLAB?在 MATLAB 中加载文本文件?
【发布时间】:2012-01-09 11:43:58
【问题描述】:

我有一个逗号分隔的文件,它有 182 行和 501 列,其中 500 列是数字类型(特征),而最后一列是字符串(标签)。

示例:182x501 尺寸

1,3,4,6,.........7, ABC
4,5,6,4,.........9, XYZ
3,4,5,3,.........2, ABC 

如何加载此文件,以便它有一个数据集,其中包含一个矩阵 B,其中包含数字作为我的特征,以及一个向量 C,其中包含字符串作为我的标签?

d = dataset(B, C);

【问题讨论】:

    标签: matlab file-io


    【解决方案1】:

    根据列的数量和类型为 textscan 构建格式说明符,并让它为您读取文件。

    nNumberCols = 500;
    format = [repmat('%f,', [1 nNumberCols]) '%s'];
    fid = fopen(file);
    x = textscan(fid, format);
    fclose(fid);
    B = cat(2, x{1:nNumberCols});
    C = x{end};
    

    【讨论】:

      【解决方案2】:

      您可以使用textscan 函数。例如:

      fid = fopen('test.dat');
      
      % Read numbers and string into a cell array
      data = textscan(fid, '%s %s');
      
      % Then extract the numbers and strings into their own cell arrays
      nums = data{1};
      str  = data{2};
      
      % Convert string of numbers to numbers
      for i = 1:length(str)
          nums{i} = str2num(nums{i}); %#ok<ST2NM>
      end
      
      % Finally, convert cell array of numbers to a matrix
      nums = cell2mat(nums);
      
      fclose(fid);
      

      请注意,我在这里根据您指定的文件格式做了一些假设。例如,我假设数字后面的逗号后面没有空格,但每行末尾的字符串前面有一个空格。

      To 可以通过使用更深思熟虑的格式说明符(textscan 的第二个参数)使上述代码更加灵活。请参阅textscan 文档中的Basic Conversion Specifiers 部分。

      【讨论】:

        【解决方案3】:

        例如,如果您在名为data.txt 的文件中有以下数据:

        1,3,4,6,7, ABC
        4,5,6,4,9, XYZ
        3,4,5,3,2, ABC 
        

        您可以使用代码将其读入矩阵B 和元胞数组C

        N = 5; % Number of numeric data to read
        fid = fopen('data.txt');
        B = []; C = {};
        while ~feof(fid)  % repeat until end of file is reached
          b = fscanf(fid, '%f,', N); % read N numeric data separated by a comma
          c = fscanf(fid, '%s', 1);  % read a string
          B = [B, b];
          C = [C, c];
        end
        C
        B
        fclose(fid);
        

        给予

        C = 
          'ABC'    'XYZ'    'ABC'
        B =
         1     4     3
         3     5     4
         4     6     5
         6     4     3
         7     9     2
        

        【讨论】:

        • 我认为你在C=[C,c] 有一个错误...它可能应该是C={C,c},或者更可能是C(end+1)={c}。我不记得确切的语法,抱歉。
        • @eykanal。这不是错误。数组连接运算符 [] 也适用于元胞数组,您可以使用 `C = {};c = 'a';C = [C, c], C = [C, c]' 来确认。
        • 你的意思是c={'a'}; c=[c c];,但是是的,我刚刚测试过,你是对的。
        猜你喜欢
        • 2010-10-16
        • 1970-01-01
        • 2013-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-22
        • 2013-07-10
        • 2012-01-02
        相关资源
        最近更新 更多