MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   Strcmp用于MATLAB中长度不等的单元格数组 (https://www.labfans.com/bbs/showthread.php?t=23614)

poster 2019-12-10 20:42

Strcmp用于MATLAB中长度不等的单元格数组
 
是否有一种简单的方法可以在较大的字符串中找到较小的字符串单元格数组?我有两个列表,一个包含唯一元素,一个包含重复元素。我想找到较大数组中较小数组的特定模式的全部出现。我知道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]

[B]回答:[/B]

您实际上可以使用函数[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/ismember.html"]ISMEMBER[/URL]来获取一个索引向量,以了解[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/ismember.html"]largecellarray[/URL]中的单元largecellarray出现在较小数组smallcellarray ,然后使用[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/strfind.html"]STRFIND[/URL]函数(适用于字符串[I]和[/I]数字数组)在其中查找较小数组的起始索引较大的:

>> 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 使用功能[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/bsxfun.html"]BSXFUN[/URL]创建它的另一种方法是[URL="https://stackoverflow.com/questions/3152652/strcmp-for-cell-arrays-of-unequal-length-in-matlab/3155048#3155048"]Amro[/URL] 。创建它的另一种方法是:

index = cumsum([startIndices; ones(nSmall-1,numel(startIndices))]); index = ismember(1:numel(largecellarray),index);

[url=https://stackoverflow.com/questions/3152652]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 14:17

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.