Finding elements of one vector that are closest to elements of another
37 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
Weitere Antworten (1)
Adam Danz
am 5 Nov. 2020
Bearbeitet: Adam Danz
am 5 Nov. 2020
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 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!