필터 지우기
필터 지우기

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!

채택된 답변

the cyclist
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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by