查找符合许多条件的元素 [英] Find elements meeting any of a number of criteria

查看:100
本文介绍了查找符合许多条件的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一个向量中与另一个向量相对应的元素索引,最好不使用循环.例如,我的输入可能是:

I am trying to find the indices of elements in a vector that correspond to another vector, preferably without using loops. For example, my input might be:

DJiSet = [5 7 8];                   % elements of which I need the indices
JiSet = [3 4 5 6 7 8 9 11 12 20];   % vector to search

这里的输出将是:

[3 5 6]

到目前为止,我想出的最快的方法是:

The fastest I've come up with so far is this:

Output = find(ismember(JiSet,DJiSet));

但是我感觉这可以更快地完成,特别是因为我认为find命令相当慢.

However I have a feeling this could be done faster, especially since I thought the find command is rather slow.

注意事项:

  • 保证DJiSet中的值都存在于JiSet
  • JiSet始终按升序排序,没有重复的条目
  • 不能保证在JiSet中连续找到向量DJiSet
  • The values in DJiSet are guaranteed to all be present in JiSet
  • JiSet is always sorted in ascending order, without repeated entries
  • The vector DJiSet is not guaranteed to be found contiguously in JiSet

推荐答案

方法1

您可以通过反转ismember中的DJiSetJiSet的位置来避免find,然后使用第二个输出为我们提供匹配的索引-

You can avoid find by reversing the places of DJiSet and JiSet inside ismember and then use the second output that gives us the matching indices -

[~,out] = ismember(DJiSet,JiSet)


方法2

可以尝试使用满足问题中特定条件的循环方法,尽管不确定这是否会更有效-

Loopy approach catering to the specific conditions set in the question could be tried out, not sure if this will be more efficient though -

intv_idx = zeros(1,numel(DJiSet));
intv_idx(1) = find(JiSet==DJiSet(1),1);
start = intv_idx(1)+1;
for k = 2:numel(DJiSet)
    idx = find(JiSet(start:end)==DJiSet(k),1);
    start = idx+start;
    intv_idx(k) = idx;
end
out = cumsum(intv_idx);

这篇关于查找符合许多条件的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆