Is there an easy way to find a smaller cell array of strings within a larger one? I’ve got two lists, one with unique elements, and one with repeating elements. I want to find whole occurrences of the specific pattern of the smaller array within the larger. I’m aware that strcmp will compare two cell arrays, but only if they’re equal in length. My first thought was to step through subsets of the larger array using a loop, but there’s got to be a better solution.
For example, in the following:
smallcellarray={'string1',...
'string2',...
'string3'};
largecellarray={'string1',...
'string2',...
'string3',...
'string1',...
'string2',...
'string1',...
'string2',...
'string3'};
index=myfunction(largecellarray,smallcellarray)
would return
index=[1 1 1 0 0 1 1 1]
You could actually use the function ISMEMBER to get an index vector for where the cells in
largecellarrayoccur in the smaller arraysmallcellarray, then use the function STRFIND (which works for both strings and numeric arrays) to find the starting indices of the smaller array within the larger:Then it’s a matter of building the vector
indexfrom these starting indices. Here’s one way you could create this vector:Another way to create it using the function BSXFUN is given by Amro. Yet another way to create it is: