MATLAB Answers

Replace the empty output of find() by the closest element

6 views (last 30 days)
Hello everyone,
I have two arrays
a1 = [t1, t2, t3, t4, t5];
a2 = [t1, t1 + d, t1 + 2 * d, t1 + 3 * d];
I use find()
for i = 1:length(a1)
indices(i) = find( a1 == a2(i) );
end
If some elements of a2 are not contained in a1, some of the find() outputs are empty. How to replace these empty elemenets by the indices of the next closest number?
I have tried
for i = 1:length(a1)
indices(i) = find( a1 == a2(i) );
if isempty(indices(i))
indices(i) = indices(i + 1);
end
end
but apparently it does not work.
Your help is highly acknowledged.

Accepted Answer

John D'Errico
John D'Errico on 24 Jan 2020
Edited: John D'Errico on 24 Jan 2020
You are trying to use the wrong tool (i.e., find) to solve this. Well, you could use find, I suppose, with some significant effort. But instead, just use a tool designed to solve that problem.
You apparently want to locate the index of the closest element in a2 to each element in a1. If there is an exact match, that is a great thing, but otherwise, you want the closest match. I'm not sure how you would resolve the case where there are two elements of a2 that are equidistant. I would think that logically, you would choose the first such match from equals.
Regardless, This is a problem solved by knnsearch.
a1 = [2, 3, 4, 5];
a2 = [1, 3, 5, 7, 9, 11];
[idx,D] = knnsearch(a2',a1')
idx =
1
2
2
3
D =
1
0
1
0
As you can see, knnsearch did exactly that.
  6 Comments
Asatur Khurshudyan
Asatur Khurshudyan on 26 Jan 2020
Thank you for your comment. I will test it, because knnsearch works very slowly.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!