⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 nearest_neighbor2.m

📁 Diversos ejemplos sobre la aplicacion de algoritmos geneticos.
💻 M
字号:
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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -