Reputation: 19
I have a matrix 50943x3 that contains vertices of a surface mesh.I want to find the index of a certain vertex using its coordinates (x,y,z).
I tried the Matlab function find but it return an empty matrix 0-by-1.
Thanks in advance,
Cheers
Upvotes: 0
Views: 519
Reputation: 1580
Try the following:
mat = randi(30,50943,3);
vec = [1,2,3];
% R2106b+ code
ind = find(all(mat==vec,2));
% or: explicit expansion, works with all versions
ind = find(all(bsxfun(@eq,mat,vec),2));
What it does:
==
or eq
will check if coordinates are equal (gives a [50943x3] bool matrix)
all
will return true only if all coordinates are equal
find
returns the index of all non zero elements
This works only for an exact match (hence the integer coordinates picked with randi
).
Since the answer is already accepted, I'll add @Zep answer that provide a solution to get the nearest point, which seem to be what was initially sought.
[min_dist,ind_nearest] = min(sum(bsxfun(@minus,mat,vec).^2,2)); % index to the nearest point
Upvotes: 1
Reputation: 1576
Your attempt probably does not work because of floating point rounding errors. You can read more about it here. You could look into the the eps function, or just use this example:
% Your matrix
M = randn(50943 , 3);
% The coordinates you are looking for
P = [0,0,0];
% Distance between all coordinates and target point
D = sqrt(sum((M - bsxfun(@minus,M,P)).^2,2));
% Closest coordinates to target
[~ , pos] = min(D);
% Display result
disp(M(pos , :))
Upvotes: 2