Paul Manta
Paul Manta

Reputation: 31567

How to generate this vector in Octave/ MATLAB?

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).

Upvotes: 0

Views: 511

Answers (2)

user677656
user677656

Reputation:

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)

Upvotes: 2

aardvarkk
aardvarkk

Reputation: 15986

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.

Upvotes: 1

Related Questions