Given two arrays A and B, how to get B values which are the closest to A.
2 ビュー (過去 30 日間)
古いコメントを表示
Suppose I have two arrays ordered in an ascending order, i.e.:
A = [1 5 7], B = [1 2 3 6 9 10]
I would like to create from B a new vector B', which contains only the closest values to A values (one for each).
I also need the indexes. So, in my example I would like to get:
B' = [1 6 9]. Idx = [1 4 5]
Note that the third value is 9. Indeed 6 is closer to 7 but it is already 'taken' since it is close to 4.
Any idea for a suitable code?
Note: my true arrays are much larger and contain real (not int) values
Thanks!
0 件のコメント
採用された回答
the cyclist
2016 年 12 月 26 日
Here is a very straightforward way to get your values of B_prime and Idx.
A = [1 5 7];
B = [1 2 3 6 9 10];
NA = length(A);
B_prime = zeros(1,NA);
B_orig = B;
for n = 1:NA
[~, j] = min(abs(A(n)-B));
B_prime(n) = B(j);
B(j) = [];
end
[~,Idx] = ismember(B_prime,B_orig);
I expect this code will run into problems if the values in B are not unique (but I did not test that for you).
After admittedly very little thought, I could not think of any easy way to vectorize this, given your requirement of not replicating elements of B.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!