Finding elements of one vector that are closest to elements of another
조회 수: 35 (최근 30일)
이전 댓글 표시
I have two vectors, x and y. Both vectors contain numbers from 0 to 1. Vector x is 964 elements. Vector y is 51 elements.
I need to find the values from vector x that are closest to the values of vector y, without replacement. So if x(1) is closest to y(1), it returns x(1) - but when it moves to find the closest element to x(2), it cannot return x(1) again and must return a different value, even if x(1) was closer to y(2) than the value it returns. Basically, I need to find the 51 unique values in x that most closely align with the values in y.
Any ideas?
Thank you!
댓글 수: 0
채택된 답변
추가 답변 (1개)
Adam Danz
2020년 11월 5일
편집: Adam Danz
2020년 11월 5일
Here's a lower-level approach (~10x faster than matchpairs but that function is also quite fast).
- Use implicit expansion to create a matix of y-x values.
- Replace the paired x-minimum with NaN so it cannot be chosen again
- Create table to show results.
Demo
% Create x,y values
rng('default') % for reproducibility
x = rand(1,964);
y = rand(1,51);
% Loop through each y-value to find x-min pair
minIdx = nan(numel(y),1);
xCopy = x;
for i = 1:numel(y)
diffs = abs(y(:)-xCopy(:).');
[~,minIdx(i)] = min(diffs(i,:));
xCopy(minIdx(i)) = NaN;
end
% Confirm at all values are unique
assert(numel(unique(minIdx))==numel(minIdx), 'Index values are not unique.')
% Show pairs
T = table(y(:), x(minIdx)', y(:)-x(minIdx)', minIdx(:), ...
'VariableNames', {'y','xMin','y-x','xMinIndex'})
The table shows the original y-values, the paired x-minimum values, the difference between y-x (absolute), and the index of x that paired with y.
Plot the results comparing y to the paird x values and use color to indicate the difference between y and x.
figure()
scatter(T.xMin, T.y, 60, T.('y-x'), 'LineWidth', 1.5)
xlabel('x-pair')
ylabel('y')
colormap('jet')
cb = colorbar();
ylabel(cb, '|y-x|')
axis equal
grid on
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!