expanding arrays to take all permutations for add/subtract operations
조회 수: 8 (최근 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)
댓글 수: 0
답변 (1개)
Andrei Bobrov
2015년 5월 18일
distance = 1./squeeze(sum(bsxfun(@minus,a,permute(b,[3, 2, 1])).^2,2));
댓글 수: 1
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!