【发布时间】:2015-11-23 07:19:55
【问题描述】:
问题:我有两个大的字符串数组A 和B。我想知道识别A 中哪些元素包含B 中哪些元素的最快方法。尤其是不循环可以做到吗?
最小示例:(我的实际 A 和 B 分别包含 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 的行和列分别对应A 和B 的元素。就我的目的而言,如果C 返回where 中的字符串B 位于A 中的第一个索引,我只需要一个真/假答案,例如:
C = [ 0 0 0 ;
0 0 0 ;
4 0 3 ;
0 0 4 ];
我尝试过的: This 帖子类似,只是他们正在寻找字符串排除其他字符串,因此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 可以帮忙吗?我卡在循环中了吗?
【问题讨论】:
-
所以你的输出矩阵应该是 7,000,000 x 22,000 矩阵?这听起来不像是可以在内存方面处理的矩阵。
标签: string matlab vectorization cell-array