nearest_neighbor2.m

来自「Diversos ejemplos sobre la aplicacion de」· M 代码 · 共 50 行

M
50
字号
function [y, i, d] = nearest_neighbor2(x, A)
% function [y, i, d] = nearest_neighbor(x, A)
%
% Find the row vector y from a matrix of row vectors A
% that is closest in Euclidean distance to row vector x. 

%
%   Inputs:
%     x: a vector of numbers of size 1 x n
%     A: k vectors of size 1 x n, "stacked" in a k x n matrix
%
%   Outputs:
%     y: the closes vector in A to x (of size 1 x n)
%     i: the integer (row) index of y in A
%     d: the Euclidean distance between x and y

[xr, xc] = size(x);
[Ar, Ac] = size(A);

if (xc ~= Ac)
   error('input vector x and matrix A must have the same number of columns');
end

if (xr ~= 1)
   error('input vector x must be a row vector');
end

% VECTORIZED VERSION OF THE CODE
% create a matrix of size Ar x xc, where each row consists
% of x
xmatrix = repmat(x,Ar,1);

% subtract the components of xmatrix and A, by matrix
% subtraction
delta = xmatrix - A;

% now square the differences, by component multiplication
squaredelta = delta.*delta;

% sum up the squared differences, row by row (note use of
% transpose: ')
distances = sqrt(sum(squaredelta')');

% find the minimum distance and its location (as before)
[d i] = min(distances);
% find the vector (the row in A) corresponding to the
% minimum distance
y = A(i,:);

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?