简体   繁体   中英

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.

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. I have already tried method ismember .

You can compute distances with pdist2 , obtain the minimum, and then find all rows that have minimum distance:

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.


Depending on your definition of distance you could use bsxfun instead of pdist2 . For example, for (squared) Euclidean distance,

dist = sum(bsxfun(@minus, vector, matrix(:,1:numel(vector))).^2, 2); %// squared distance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM