【问题标题】:MATLAB search cell array for string subsetMATLAB 在元胞数组中搜索字符串子集
【发布时间】:2012-03-14 18:50:12
【问题描述】:

我正在尝试在 MATLAB 的元胞数组中查找子字符串出现的位置。下面的代码有效,但相当难看。在我看来应该有一个更简单的解决方案。

cellArray = [{'these'} 'are' 'some' 'nicewords' 'and' 'some' 'morewords'];
wordPlaces = cellfun(@length,strfind(cellArray,'words'));
wordPlaces = find(wordPlaces); % Word places is the locations.
cellArray(wordPlaces);

这与thisthis 相似,但又不同。

【问题讨论】:

    标签: string matlab cell


    【解决方案1】:

    我不知道您是否会认为它比您的解决方案更简单,但regular expressions 是我经常用于搜索字符串的非常好的通用实用程序。从cellArray 中提取包含'words' 单词的单元格的一种方法如下:

    >> matches = regexp(cellArray,'^.*words.*$','match');  %# Extract the matches
    >> matches = [matches{:}]                              %# Remove empty cells
    
    matches = 
    
        'nicewords'    'morewords'
    

    【讨论】:

    • 优秀的解决方案,但我害怕正则表达式。它的代码行数较少,但我已将上述内容标记为正确,因为我宁愿避免使用正则表达式。抱歉,这感觉有点不公平,因为这是正确的,并且在某种意义上更简单。
    • @dgmp88:我完全理解。正则表达式确实需要一些时间来适应,但一旦你掌握了它们,你feel like a superhero。 ;)
    【解决方案2】:

    要做的就是把这个想法封装成一个函数。内联:

    substrmatch = @(x,y) ~cellfun(@isempty,strfind(y,x))
    
    findmatching = @(x,y) y(substrmatch(x,y))
    

    或包含在两个 m 文件中:

    function idx = substrmatch(word,cellarray)
        idx = ~cellfun(@isempty,strfind(word,cellarray))
    

    function newcell = findmatching(word,oldcell)
        newcell = oldcell(substrmatch(word,oldcell))
    

    所以现在你可以输入

    >> findmatching('words',cellArray)
    ans = 
        'nicewords'    'morewords'
    

    【讨论】:

    • 干杯!那行得通,但问题是我希望有一个内置的功能,或者至少有一种方法可以用更少的步骤来完成。如果有人想出了很棒的东西,如果没有,我会在几个小时内将其标记为解决方案。
    • 据我所知没有内置函数。不久前我自己也遇到了同样的问题,最后写了这些代码 sn-ps 因为我找不到可以满足我想要的内置。
    猜你喜欢
    • 2011-12-25
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    相关资源
    最近更新 更多