Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

matlab - Find elements meeting any of a number of criteria

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

The output here would be:

[3 5 6]

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

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

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

Things to note:

  • 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Approach #1

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)

Approach #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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...