- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
问题:我有两个大型字符串元胞数组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 post 是类似的,除了他们正在寻找字符串排除 其他字符串,因此 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
关于string - 批量 strfind : finding lots of strings within lots of other strings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33865570/
我有一个 1x5 的单元格,它看起来像这样: A = {'asd','pqr','asd 123','pqr123','asd 1','dfg',} 当我这样做时: strfind(A,'asd')
我想在 strfind 函数上使用 cellfun 函数来查找另一个字符串元胞数组中字符串元胞数组中每个字符串的索引,以将它们从中排除. strings = {'aaa','bbb','ccc','d
问题:我有两个大型字符串元胞数组A 和B。我想知道识别 A 中哪些元素包含 B 中哪些元素的最快方法。特别是不循环能不能做到? 最小示例:(我的实际 A 和 B 分别包含 7,000,000 和 22
出于某种原因 size(strfind(n,',')) 数字 44 很特殊,会产生逗号查找结果: value={55} numCommas = size(strfind(value{1},','),2
对于 AIX 中的 gcc 编译器,我们是否有替代 strrspn 和 strfind 函数(Solaris 中的 libgen 函数)的替代方案? 下面提到了这些功能 - int strfind(c
我是一名优秀的程序员,十分优秀!