【问题标题】:comparing strings in matlab在matlab中比较字符串
【发布时间】:2020-04-26 02:00:36
【问题描述】:

我有一个大字符串(已经排序),由类似的单元格组成

batch = [{'a'},{'a'},{'a'},{'m'},{'m'},{'q'},{'q'},{'q'},{'q'}]

在 for 循环中,我需要 batch 中的索引,比如出现 val = {'a'},也就是说,我正在批量迭代不同的字符串——在这种情况下是 {'a'}, {'m'}, {'q'}

使用诸如ismemberstrcmp 或简单的find 之类的fcn 显然有效,例如find(ismember(batch, val)) 但是,这对我的目的来说太慢了。是否可以在 for 循环之外找到 val 出现在 batch 中的开始和最后一个索引,然后我可以在 for 循环中调用这些索引?谢谢你。

【问题讨论】:

  • [{'a'},{'a'},{'a'},{'m'},{'m'},{'q'},{'q'},{'q'},{'q'}]{'a','a','a','m','m','q','q','q','q'} 相同,但更加乏味和冗长。

标签: string matlab cell


【解决方案1】:

我们可以做一个计时实验:

batch = [{'a'},{'a'},{'a'},{'m'},{'m'},{'q'},{'q'},{'q'},{'q'}];
val = {'a'}
% make the array to be searched in longer for relevant timing
Str = repmat(batch,1,1000000);
% ismember
tic
idx = find(ismember(Str,val));
toc
% strcmp
tic
idx = find(strcmp(Str,val));
toc
% contains
tic
idx = find(contains(Str,val));
toc
% cellfun/isequal
tic
idx = find(cellfun(@(x)isequal(x,val),Str));
toc
% looping
tic
idx = NaN(round(length(Str)/4),1);
k = 1;
for i = 1:length(Str)
    lg = Str{i} == val{1};
    if lg
        idx(k) = i;
        k = k+1;
    end
end
idx = idx(1:k-1);
toc

导致在我的机器上

  • 经过的时间是 0.266673 秒。 % 是会员
  • 经过的时间为 0.225149 秒。 % strcmp
  • 经过的时间是 0.144104 秒。 % 包含
  • 经过的时间是 50.683212 秒。 % cellfun + isequal
  • 经过的时间是 1.689111 秒。 % loopint + isequal

如果使用 sting-array 而不是元胞数组,情况会更糟。

但是,我无法想象这些功能对您来说太慢了。但我可以想象你想要这样做的原因不是最佳的......所以分享更多信息和代码来加速整个问题,而不仅仅是这个子问题(但为此打开一个新问题;))

【讨论】:

  • 有时间的答案总是很好! (+1)。但考虑到输入字符串已排序,您可以使用循环做得更好。例如,二分搜索。会是更复杂的代码,但对于大数据可能会更快。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-06
  • 2011-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多