[英]How to find a row in matrix containing closest values to given vector in Matlab
I am writing a function to find a row in matrix which is closest to given vector and given vector can be variable in size. 我正在写一个函数来查找矩阵中最接近给定向量的行,并且给定向量的大小可以变化。 For example if matrix size is by 4 and vector size is 3 then function will check the first three values form each row of matrix. 例如,如果矩阵大小为4,向量大小为3,则函数将检查矩阵的每一行的前三个值。
For comparison, I am calculating the distance of each row in matrix from given vector and then selecting the row which has minimum distance but I think this is not perfect solution because two different row can have same minimum distance from given vector. 为了进行比较,我正在计算距给定矢量的矩阵中每一行的距离,然后选择具有最小距离的行,但是我认为这不是完美的解决方案,因为两个不同的行距给定矢量可以具有相同的最小距离。
I would like to know that is there any built in function available in matlab. 我想知道在matlab中有可用的内置函数。 I have already tried method ismember
. 我已经尝试过方法ismember
。
You can compute distances with pdist2
, obtain the minimum, and then find all rows that have minimum distance: 您可以使用pdist2
计算距离,获取最小距离,然后找到所有具有最小距离的行:
vector = [1 3 2];
matrix = [2 1 2 2
1 3 3 4
0 0 0 0
5 4 3 2]; %// example data
dist = pdist2(vector, matrix(:,1:numel(vector)), 'euclidean'); %// compute distances
mindist = min(dist); %// minimum distance
result = find(dist==mindist); %// minimizing rows
Change 'euclidean'
in pdist2
to use other distance definitions. 在pdist2
'euclidean'
pdist2
'euclidean'
更改为使用其他距离定义。
Depending on your definition of distance you could use bsxfun
instead of pdist2
. 根据您对距离的定义,可以使用bsxfun
而不是pdist2
。 For example, for (squared) Euclidean distance, 例如,对于(平方)欧几里德距离,
dist = sum(bsxfun(@minus, vector, matrix(:,1:numel(vector))).^2, 2); %// squared distance
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.