【问题标题】:read complicated .txt file into Matlab将复杂的 .txt 文件读入 Matlab
【发布时间】:2011-06-03 21:00:32
【问题描述】:

我想将一个 .txt 文件读入 Matlab。 其中一列包含字母和数字。 (所以我想一种方法是将此列读取为字符串。)

问题是我还需要找出该列中大于 5 的数字。

例如.txt 看起来像

12 1
21 2
32 7
11 a
03 b
22 4
13 5
31 6

即最终,我想得到 ​​p>

32 7
31 6

我怎样才能得到它?请哪位高手帮忙!

【问题讨论】:

    标签: string matlab file-io textscan


    【解决方案1】:

    您可以使用TEXTSCAN 将文件的内容读入字符串元胞数组,使用CELLFUNSTR2NUM 将字符串转换为数值('a''b' 等字符将导致空矩阵 []),删除单元格数组中包含任何空单元格的行,然后使用 CELL2MAT 将剩余数据转换为 N×2 矩阵:

    fid = fopen('junk.txt','r');                        %# Open the file
    data = textscan(fid,'%s %s','CollectOutput',true);  %# Read the data as strings
    fclose(fid);                                        %# Close the file
    data = cellfun(@str2num,data{1},'UniformOutput',false);  %# Convert to numbers
    data(any(cellfun('isempty',data),2),:) = [];        %# Remove empty cells
    data = cell2mat(data);                              %# Convert to N-by-2 array
    

    考虑到问题中的示例文件,矩阵data 现在看起来像这样:

    >> data
    
    data =
    
        12     1
        21     2
        32     7
        22     4
        13     5
        31     6
    

    您可以像这样在第二列中获取值大于 5 的行:

    >> data(data(:,2) > 5,:)
    
    ans =
    
        32     7
        31     6
    

    【讨论】:

      【解决方案2】:
      fid = fopen('txt.txt','r');  
      
      Aout = []; 
      
      while(1)    
          [a1,count1] = fscanf(fid,'%s',1);
          [a2,count2] = fscanf(fid,'%s',1);
          if(count1 < 1 | count2 < 1)
              break;    
          end
          if(~isempty(str2num(a2)) & str2num(a2) > 5 & (~isempty(str2num(a1))) )
              Aout = [ Aout ; str2num(a1) str2num(a2) ];   
          end
      end
      
      fclose(fid);
      

      违反了在循环期间增加 Matlab 变量的潜规则,但无论如何它是文本处理,因此您可能不会注意到速度缓慢。

      编辑:以前的版本有太多错误,必须重新开始。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-30
        • 1970-01-01
        • 1970-01-01
        • 2012-07-29
        • 2018-04-12
        • 1970-01-01
        相关资源
        最近更新 更多