matlab - MATLAB 中不等长元胞数组的 Strcmp

标签 matlab strcmp cell-array

有没有一种简单的方法可以在较大的字符串元胞数组中找到较小的字符串元胞数组?我有两个列表,一个包含唯一元素,一个包含重复元素。我想在较大的数组中找到较小数组的特定模式的全部出现。我知道 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 中单元格在较小数组 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);

关于matlab - MATLAB 中不等长元胞数组的 Strcmp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3152652/

相关文章:

arrays - 在 MATLAB 中一次为元胞数组分配不同的值

c++ - 从Octave CLI构建mex文件

c - strcmp 对于 2 个确切的文件不返回 0

c - 字符串比较有问题

c - 使用 strtok() 和 strcmp() 出现段错误

arrays - MATLAB:如何拆分不同分隔符数字的元胞数组?

arrays - 将各种大小的元胞数组的元胞数组整理成大小为 {1xN} 的元胞数组的元胞数组

python - 删除 NumPy 中的所有其他元素

c++ - 如何将文件路径变量传递给 mex 命令?

matlab - 在 Julia(或 Matlab)中绘制投资组合构成图