是否有一种简单的方法可以在较大的字符串中找到较小的字符串单元格数组?我有两个列表,一个包含唯一元素,一个包含重复元素。我想找到较大数组中较小数组的特定模式的全部出现。我知道strcmp会比较两个单元格数组,但前提是它们的长度相等。我的第一个想法是使用循环逐步遍历更大数组的子集,但是必须有一个更好的解决方案。
例如,在下面:
smallcellarray={'string1',... 'string2',... 'string3'}; largecellarray={'string1',... 'string2',... 'string3',... 'string1',... 'string2',... 'string1',... 'string2',... 'string3'}; index=myfunction(largecellarray,smallcellarray) 会回来
index=[1 1 1 0 0 1 1 1]
回答:
您实际上可以使用函数
ISMEMBER来获取一个索引向量,以了解
largecellarray中的单元largecellarray出现在较小数组smallcellarray ,然后使用
STRFIND函数(适用于字符串
和数字数组)在其中查找较小数组的起始索引较大的:
>> nSmall = numel(smallcellarray); >> [~, matchIndex] = ismember(largecellarray,... %# Find the index of the smallcellarray); %# smallcellarray entry %# that each entry of %# largecellarray matches >> startIndices = strfind(matchIndex,1:nSmall) %# Starting indices where the %# vector [1 2 3] occurs in startIndices = %# matchIndex 1 6 然后,需要从这些起始索引构建向量index 。这是创建此向量的一种方法:
>> nLarge = numel(largecellarray); >> endIndices = startIndices+nSmall; %# Get the indices immediately after %# where the vector [1 2 3] ends >> index = zeros(1,nLarge); %# Initialize index to zero >> index(startIndices) = 1; %# Mark the start index with a 1 >> index(endIndices) = -1; %# Mark one index after the end with a -1 >> index = cumsum(index(1:nLarge)) %# Take the cumulative sum, removing any %# extra entry in index that may occur index = 1 1 1 0 0 1 1 1 使用功能
BSXFUN创建它的另一种方法是
Amro 。创建它的另一种方法是:
index = cumsum([startIndices; ones(nSmall-1,numel(startIndices))]); index = ismember(1:numel(largecellarray),index);
更多&回答...