Существует ли простой способ найти меньший массив ячеек строк в большей? У меня есть два списка, один с уникальными элементами, и один с повторяющимися элементами. Я хочу найти целые случаи определенного шаблона меньшего массива в большем. Я знаю, что 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);
Вот моя версия (на основе ответов @yuk и @gnovice):
g = grp2idx([S L])';
idx = strfind(g(numel(S)+1:end),g(1:numel(S)));
idx = bsxfun(@plus,idx',0:numel(S)-1);
index = zeros(size(L));
index(idx(:)) = 1;
В ответе @gnovice первая часть может быть
l = grp2idx(largecellarray)';
s = grp2idx(smallcellarray)';
startIndices = strfind(l,s);
Я получил следующее решение работает, но мне все еще интересно, есть ли лучший способ сделать это:
function [output]=cellstrcmpi(largecell,smallcell)
output=zeros(size(largecell));
idx=1;
while idx<=length(largecell)-length(smallcell)+1
if sum(strcmpi(largecell(idx:idx+length(smallcell)-1),smallcell))==length(smallcell)
output(idx:idx+length(smallcell)-1)=1;
idx=idx+length(smallcell);
else
idx=idx+1;
end
end
(Я знаю, я знаю, без проверки ошибок - я ужасный человек.)