【问题标题】:Performing find and replace functions on elements of a table in Matlab在 Matlab 中对表格的元素执行查找和替换功能
【发布时间】:2015-08-19 20:51:43
【问题描述】:

我正在处理一个 400x1200 的导入表(从 .xls 生成的可读表),其中包含字符串、双精度数、日期和 NaN。每一列的键入一致。我正在寻找一种方法来定位任何给定字符串的表中的所有实例(“请帮帮我”)并将它们全部替换为双精度 (1)。在 Matlab 中执行此操作将节省我大量更改本项目其余部分使用的方法的工作量。

不幸的是,我看过的所有选项(regexp、strrep 等)都只能使用字符串作为替换。 Strfind 同样没有帮助,因为在桌子上打字。缺乏 cellfun 也使这比应有的更难。我知道解决方案应该与查找我想要的字符串的索引然后循环 DataFile{subscript} = [1] 有关,但我找不到方法。

【问题讨论】:

  • 发布一些你迄今为止尝试过的代码。
  • strcmp 呢?
  • 其实你可以cellfuntable2cell结合使用。

标签: matlab str-replace


【解决方案1】:

首先,您应该将表格转换为元胞数组。

然后,您可以将strrepstr2num 一起使用,例如

% For a given cell index
strrep(yourCellIndexVariable, "Help me please", "1");
str2num(yourCellIndexVariable);

这会将字符串“请帮帮我”替换为字符串“1”(strrep 函数),str2num 将根据字符串将单元格索引更改为双精度值。

yourCellIndexVariable 指的是元胞数组中的一个元素。有几种方法可以从单元阵列中获取所有单元,但我认为您已经解决了该部分。

【讨论】:

    【解决方案2】:

    你可以做的如下:

    [rows, cols] = size(table); % Get the size of your table
    YourString = 'Help me please'; % Create your string
    Strmat = repmat(YourString,rows,cols); % Stretch to fill a matrix of table size
    TrueString = double(strcmp(table,Strmat)); % Compares all entries with one another
    

    TrueString 现在包含逻辑,1 表示字符串“请帮助我”所在的位置,0 表示不存在的位置。

    如果您有一个包含多个类的表格,那么切换到单元格可能会很方便。

    【讨论】:

      【解决方案3】:

      非常感谢大家帮助我们思考解决方案。这是我最终得到的结果:

      % Reads data
      [~, ~, raw] = xlsread ( 'MyTable.xlsx');
      MyTable = raw;
      
      % Makes a backup of the data in table form
      MyTableBackup = readtable( 'MyTable.xlsx' );
      
      % Begin by ditching 1st row with variable names
      MyTable(1,:) = [];
      
      % wizard magic - find all cells with strings
      StringIndex = cellfun('isclass', MyTable, 'char');
      
      % strrep goes here to recode bad strings. For example:
      MyTable(StringIndex) = strrep(MyTable(StringIndex), 'PlzHelpMe', '1');
      
      % Eventually, we are done, so convert back to table
      MyTable = cell2table(MyTable);
      
      % Uses backup Table to add variable names
      % (the readtable above means the bad characters in variable names are already escaped!) 
      MyTable.Properties.VariableNames = MyTableBackup.Properties.VariableNames;
      

      这意味着新值作为字符串存在('1',而不是 1 作为双精度数),所以现在我在访问它们进行分析时只需 str2double。我的收获——Matlab 是用于数字的。再次感谢大家!

      【讨论】:

        猜你喜欢
        • 2017-09-12
        • 1970-01-01
        • 2011-02-04
        • 1970-01-01
        • 2016-11-05
        • 1970-01-01
        • 2018-04-17
        • 2019-02-20
        • 2022-06-15
        相关资源
        最近更新 更多