expanding arrays to take all permutations for add/subtract operations

7 次查看(过去 30 天)
a = reshape(1:9,3,3)
b = reshape(0:0.1:0.5,2,3)
arows = size(a,1);
brows = size(b,1);
for m = 1:arows
for n = 1:brows
c(m,n,:) = a(m,:) - b(n,:);
end
end
distance = 1./sqrt(sum(c.^2,3))
I want to calculate the Euclidean distance of all combinations of points in two coordinate arrays, a (mx3) and b (nx3). I know how to do this in a loop (see above), but is there some nice/fast/readable vectorized operation that lets me do this, sort of how vector outer products lets you expand to all permutations of elementwise multiplication?
(1:3)'*(1:5)
ans =
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
Obviously, I could expand each dimension, but I don't think that is very readable:
x = repmat(a(:,1), 1, brows) - repmat(b(:,1)', arows, 1);
y = repmat(a(:,2), 1, brows) - repmat(b(:,2)', arows, 1);
z = repmat(a(:,3), 1, brows) - repmat(b(:,3)', arows, 1);
distance = 1./sqrt(x.^2+y.^2+z.^2)

回答(1 个)

Andrei Bobrov
Andrei Bobrov 2015-5-18
distance = 1./squeeze(sum(bsxfun(@minus,a,permute(b,[3, 2, 1])).^2,2));
  1 个评论
Victor
Victor 2017-5-5
Haha his complaint about the more explicit solution was readability.. This is some seriously cryptic, 'matic code. I can't wait to confuse my coworkers with this one, seems to do the business.

请先登录,再进行评论。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by