nearest_neighbor1.m

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

M
39
字号
function [y, i, d] = nearest_neighbor1(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

% "for loop" version of code
% distances = zeros(Ar,1)   % preallocate storage for distances
for j=1:Ar    % loop over rows in A
   y = A(j,:);
   distances(j) = euclidean(x,y);
end
% find the minimum distance and its location
[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 + -
显示快捷键?