简体   繁体   中英

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

所以,你有3D质心和三维点,并希望任何点数PTpoints来确定所有质心的距离。

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

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.

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