MATLAB: Sorting arrays after finding closest values

arraysMATLABresizingsorting

Hi, I am trying to find a way to find the closest 2,3,4 values inside two sets of (x,y) values to each number in a set of three values. The three values are X values so I just need to find the closest X values and then resize the X and the Y arrays. I was thinking of using the knnsearch function but I'm not sure if that works since the three values (x1 array) would not match up with the 6 values.
x = [1 2 3 5 7 8]; % x values
y = [3 6 19 99 291 444]; % y values
x1 = [2.8 4.4 7.1]; % find the closest 2,3,4 x points to each x1 and then resize x and y arrays
% into 2,3,4 values
%% so for 2.8 (2 closest), x = [2 3] , y =[6 19]
%% 2.8 ( 3 closest), x = [1 2 3], y = [3 6 19]

Best Answer

Try this:
x = [1 2 3 5 7 8]; % x values
y = [3 6 19 99 291 444]; % y values
x1 = [2.8 4.4 7.1]; % find the closest 2,3,4 x points to each x1 and then resize x and y arrays
% into 2,3,4 values
%% so for 2.8 (2 closest), x = [2 3] , y =[6 19]
%% 2.8 ( 3 closest), x = [1 2 3], y = [3 6 19]
for k = 1 : length(x1)
thisX1 = x1(k);
distances = abs(x - thisX1);
[sortedDistances, sortOrder] = sort(distances, 'ascend');
% Find closest 2:
fprintf('\nFor x1 = %.1f, the 2 closet x values are %.1f and %.1f, and the y values are %.1f and %.1f.\n', ...
thisX1, x(sortOrder(1)), x(sortOrder(2)), y(sortOrder(1)), y(sortOrder(2)));
% Find closest 3:
fprintf('For x1 = %.1f, the 3 closet x values are [%.1f, %.1f, %.1f], and the y values are [%.1f, %.1f, %.1f].\n', ...
thisX1, x(sortOrder(1)), x(sortOrder(2)), x(sortOrder(3)), y(sortOrder(1)), y(sortOrder(2)), y(sortOrder(4)));
% Find closest 4:
fprintf('For x1 = %.1f, the 4 closet x values are [%.1f, %.1f, %.1f, %.1f], and the y values are [%.1f, %.1f, %.1f, %.1f].\n', ...
thisX1, x(sortOrder(1)), x(sortOrder(2)), x(sortOrder(3)), x(sortOrder(4)), y(sortOrder(1)), y(sortOrder(2)), y(sortOrder(4)), y(sortOrder(4)));
end
and you'll see
For x1 = 2.8, the 2 closet x values are 3.0 and 2.0, and the y values are 19.0 and 6.0.
For x1 = 2.8, the 3 closet x values are [3.0, 2.0, 1.0], and the y values are [19.0, 6.0, 99.0].
For x1 = 2.8, the 4 closet x values are [3.0, 2.0, 1.0, 5.0], and the y values are [19.0, 6.0, 99.0, 99.0].
For x1 = 4.4, the 2 closet x values are 5.0 and 3.0, and the y values are 99.0 and 19.0.
For x1 = 4.4, the 3 closet x values are [5.0, 3.0, 2.0], and the y values are [99.0, 19.0, 291.0].
For x1 = 4.4, the 4 closet x values are [5.0, 3.0, 2.0, 7.0], and the y values are [99.0, 19.0, 291.0, 291.0].
For x1 = 7.1, the 2 closet x values are 7.0 and 8.0, and the y values are 291.0 and 444.0.
For x1 = 7.1, the 3 closet x values are [7.0, 8.0, 5.0], and the y values are [291.0, 444.0, 19.0].
For x1 = 7.1, the 4 closet x values are [7.0, 8.0, 5.0, 3.0], and the y values are [291.0, 444.0, 19.0, 19.0].