0
votes

I have a vector centroids of size n and a vector points of size p (both of these are actually Vx3 matrices, where V is the number of points or centroids).

For any given point pt from points, I want to generate another vector of distances: the distance of pt from each centroid.

Is there any functional-programming style way of doing this? Something like this, maybe (Python-style):

distances = [ norm(pt - c) for c in centroids ]

If not, what is the nicest way for me to do this? I'm using Octave, but I added the tag as well since the languages are quire similar (from what I can see, at least).

2
Have you looked at L2_distance: web.mit.edu/cocosci/isomap/code/L2_distance.m ? I think that might be helpful for sufficiently small matrices.Paul
@Paul This is an assignment and I can't include other files than what is explicitly allowed. I wanted to know what is the shortest way to generate this list of distances. :)Paul Manta

2 Answers

1
votes

I have a longer solution than g24l... I'm not sure which MATLAB versions arrayfun is valid for, so this should work on older ones:

pt = rand(1,3);
centroids = rand(2,3);
pt = repmat(pt, [size(centroids,1) 1]); % duplicate your point to vectorize
dists = sum((pt - centroids).^2,2)

All you'd have to do is wrap this in a function that takes a single pt and a matrix of centroids and you'd have your solution.

2
votes

So you have 3D centroids and 3D points, and you want for any points pt in points to determine the distance from all centroids.

arrayfun(@(x) norm(x),pt(ones(v,1),:)-centroids)