MATLAB搜索单元格数组以获取字符串子集 [英] MATLAB search cell array for string subset

查看:281
本文介绍了MATLAB搜索单元格数组以获取字符串子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在MATLAB的单元格数组中查找子字符串出现的位置.下面的代码可以工作,但是很难看.在我看来,应该有一个更简单的解决方案.

I'm trying to find the locations where a substring occurs in a cell array in MATLAB. The code below works, but is rather ugly. It seems to me there should be an easier solution.

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

这与.

推荐答案

要做的是将这个想法封装为一个函数.要么内联:

The thing to do is to encapsulate this idea as a function. Either inline:

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

findmatching = @(x,y) y(substrmatch(x,y))

或包含在两个m文件中:

Or contained in two m-files:

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'

这篇关于MATLAB搜索单元格数组以获取字符串子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆