How do I find closest values between 2 matrices?

1 view (last 30 days)
Lets say I have defined values like this:
true_ang = [-40 -20];
After passing through an algorithm, my output are polynomial roots such as this:
rts = roots(cc)
rts = 6×1 complex
-0.048729197855492 - 1.282493377891869i
-0.029583698890964 - 0.778607069086665i
0.409971042365044 + 0.917186264825464i
0.406190666466556 + 0.908728816636128i
-0.461769455823652 + 0.941122806650886i
-0.420194118738174 + 0.856388969382348i
This is followed by converting to angle form:
all_angs = -asin(angle(rts)/pi)*180/pi
all_angs = 6×1
30.803049614608504
30.803049614608490
-21.481431164796401 (this)
-21.481431164797179
-40.180359320706906 (this)
-40.180359320706934
My question is, how do I automatically obtain the closest values from all_angs to true_ang (which I've denoted at the sideas "this")? Note that the order of the results can be random.

Accepted Answer

KSSV
KSSV on 20 Mar 2019
Read about knnsearch
true_ang = [-40 -20];
all_angs = [ 30.803049614608504
30.803049614608490
-21.481431164796401
-21.481431164797179
-40.180359320706906
-40.180359320706934] ;
idx = knnsearch(all_angs,true_ang') ;
all_angs(idx)

More Answers (1)

Stephen23
Stephen23 on 20 Mar 2019
Edited: Stephen23 on 20 Mar 2019
Using basic MATLAB only (i.e. without knnsearch from the Statistics Toolbox):
>> true_ang = [-40,-20];
>> all_angs = [30.803049614608504,30.803049614608490,-21.481431164796401,-21.481431164797179,-40.180359320706906,-40.1803
59320706934];
>> [~,idx] = min(abs(true_ang - all_angs(:)),[],1);
>> all_angs(idx)
ans =
-40.180359320706906 -21.481431164796401

Categories

Find more on Get Started with Statistics and Machine Learning Toolbox in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!