【问题标题】:Filter on words in Matlab tables (as in Excel)过滤 Matlab 表格中的单词(如在 Excel 中)
【发布时间】:2015-04-12 09:20:05
【问题描述】:

在 Excel 中,您可以使用“过滤器”功能来查找列中的某些字词。我想在 Matlab 中对整个表格执行此操作。

以 Matlab 示例表“patients.dat”为例;我的第一个想法是使用:

patients.Gender=={'Female'}

这不起作用。

strcmp(patients.Gender,{'Female'})

只在一列中工作(“性别”)。

我的问题:我有一张桌子,上面有不同的单词,比如'A'、'B'、'bananas'、'apples'、.... 以任意方式分布在表格的列中。我只想要包含“A”和“B”的行。

奇怪的是,我没有在 matlab 的“帮助”中找到这个,因为它看起来很基础。我查看了stackedO,但也没有找到答案。

【问题讨论】:

  • 绝对按照@Benoit_11 的建议使用regexpstrcmp 一次只能比较一个字符串。但是,您可以使用strcmp,如果您遍历表中的所有列并创建一个单元格数组,其中每个单元格将检索每列中与您查找的内容匹配的行。
  • 我意识到我可以使用 for 循环,使用问题中所述的 strcmp 示例一次浏览一行。
  • rayryeng,我找不到你提到的@Benoit_11 示例。
  • 看起来他删除了他的评论,但这无关紧要。他只是问你是否尝试过使用strcmpregexp
  • 好的 :) 我的问题不是我无法编写解决方案(比如使用 for 循环)。我的问题是我非常沮丧,因为我找不到一个好的方法来做到这一点。我只是想过滤一个单词表。在excel中这很简单。在matlab中?更简单??

标签: matlab matlab-table


【解决方案1】:

这里有一个更简单、更优雅的语法:

matches = ((patients.Gender =='Female') & (patients.Age > 26));
subtable_of_matches = patients(matches,:);

% alternatively, you can select only the columns you want to appear,
% and their order, in the new subtable.
subtable_of_matches = patients(matches,{'Name','Age','Special_Data'});

请注意,在此示例中,您需要确保 patients.Gender 是一个分类类型。您可以使用categorical(variable) 将变量转换为分类变量,然后将其重新分配给表变量,如下所示:

patients.Gender = categorical(patiens.Gender);

这是给你的参考:https://www.mathworks.com/matlabcentral/answers/339274-how-to-filter-data-from-table-using-multiple-strings

【讨论】:

  • 这是一个很好的解决方案 - 关于使用分类的好技巧。
【解决方案2】:

Matlab 中的table 可以看作是扩展的cell array。例如,它还允许命名列。

但是,在您的情况下,您希望搜索整个 cell array,而不关心 table 的任何额外功能。因此将其转换为table2cell

然后你想搜索某些词。您可以使用regexp,但在您提到的示例中strcmp 也足够了。两者都可以立即在 cell arrays 上工作。

最后你只需要find逻辑搜索矩阵的行。

这里的示例从 Matlab 示例数据集中获取所有“男性”和“优秀”条件下的患者的行:

patients = readtable('patients.dat');
patients_as_cellarray = table2cell(patients);
rows_male = any(strcmp(patients_as_cellarray, 'Male'), 2); % is 'Male' on any column for a specific row
rows_excellent = any(strcmp(patients_as_cellarray, 'Excellent'), 2); % is 'Excellent' on any column for a specific row
rows = rows_male & rows_excellent; % logical combination
patients(rows, :)

确实只打印出状况良好的男性患者。

【讨论】:

  • 所以在我的情况下,表格格式似乎并不是那么好用。一开始我想用表格格式的原因是为了让编码和数据管理更方便。
    现在我通过在循环中使用eval并重新排列表格来解决这个问题这样我就可以按列查看它。
    For i=1:endCol Place(:,i)=eval([‘strcmp(mytable.Val’,num2str(i),’stringToCompare’]); End 正如您所提到的,在整个单元格转换表上使用 regexp 可能更容易。我会试试的!
  • 附言。我使用 stackEdit-Editor 在上面发表评论(在那里看起来很好......)但在这里不行。对不起。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
  • 2012-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多