Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
回复
 
主题工具 显示模式
旧 2019-12-10, 20:42   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 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]

回答:

您实际上可以使用函数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);

更多&回答...
poster 当前离线   回复时引用此帖
回复


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 21:15


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