在 Matlab 中对 table 的元素执行查找和替换功能

Performing find and replace functions on elements of a table in Matlab

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

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

您可以做的事情如下:

[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 现在包含逻辑,字符串 'Help me please' 所在的位置为 1,不在的位置为 0。

如果您的 table 包含多个 类,切换到单元格可能会很方便。

首先,您应该在元胞数组中转换 table。

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

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

这会将字符串 "Help me please" 替换为字符串“1”(strrep 函数)并且 str2num 会根据字符串将单元格索引更改为双精度值.

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

非常感谢大家帮忙想出解决办法。这是我最终得到的结果:

% 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 是用来处理数字的。再次感谢大家!