User1551892
User1551892

Reputation: 3384

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.

Upvotes: 0

Views: 1332

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112769

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

Upvotes: 4

Related Questions