批量 strfind:在大量其他字符串中查找大量字符串

Batch strfind: finding lots of strings within lots of other strings

问题: 我有两个大的字符串元胞数组 AB。我想知道识别 A 中哪些元素包含 B 中哪些元素的最快方法。特别是,不循环可以吗?

最小示例:(我的实际 AB 分别包含 7,000,000 和 22,000 个字符串)

A = {'one';
     'two';
     'three';
     'four'};
B = {'ee';
     'xx';
     'r'};

示例的期望输出为

C = [ 0 0 0 ;
      0 0 0 ;
      1 0 1 ;
      0 0 1 ];

其中C的行和列分别对应于AB的元素。出于我的目的,我只需要一个 true/false 答案,但如果 C returns 的第一个索引 where [=17= 中的字符串,则加分] 在 A 中,例如:

C = [ 0 0 0 ;
      0 0 0 ;
      4 0 3 ;
      0 0 4 ];

我试过的: This post 是类似的,除了他们正在寻找字符串 excluding 其他字符串,因此 regexp 提供了一个很好的解决方案——我认为这在这里不适用。对我们来说,循环就可以了,但是太慢了:

for i=1:length(A);
    for j=1:length(B);
        C(i,j) = max([0,strfind(A{i},B{j})]); disp(C(i,j));
    end
end

或者,基本相同,但 cellfun:

AA = repmat(A,[1 length(B)]);
BB = repmat(B,[length(A) 1]);
C  = reshape(cellfun(@(a,b) max([0,strfind(a,b)]),AA(:),BB(:)),[length(A),length(B)]);

更大的例子: 我在一些更大的数组上测试了 cellfun 方法(仍然比我需要的要小):

N=10000; M=200;
A=cellstr(char(randi([97,122],[N,10])));  %// N random length 10 lowercase strings
B=cellstr(char(randi([97,122],[M,4])));   %// M random length 4 lowercase strings

tic;
AA=repmat(A,[1 length(B)]);
BB=repmat(B,[length(A) 1]);
C=reshape(cellfun(@(a,b) max([0,strfind(a,b)]),AA(:),BB(:)),[length(A),length(B)]); 
toc

Elapsed time is 21.91 seconds.

有什么想法吗? regexp 有帮助吗? ismember 有帮助吗?我卡在循环了吗?

一般来说,我建议您的预期输出矩阵在内存方面会很大,无论如何您都需要重新考虑您的方法。

如果你有一个较小的数据集,你可以这样做:

A = {'one';
     'two';
     'three';
     'four'};
B = {'ee';
     'xx';
     'r'};

%// generate indices
n = numel(A);
m = numel(B);
[xi,yi] = ndgrid(1:n,1:m);

%// matching
Ax = A(xi);
By = B(yi);
temp = regexp(Ax,By,'start');

%// localize empty cell elements
%// cellfun+@isempty is quite fast
emptyElements = cellfun(@isempty, temp);

%// generate output
out = zeros(n,m);
out(~emptyElements) = [temp{:}];

out =

     0     0     0
     0     0     0
     4     0     3
     0     0     4