pdist2 equivalent in MATLAB version 7

Here is vectorized implementation for computing the euclidean distance that is much faster than what you have (even significantly faster than PDIST2 on my machine): D = sqrt( bsxfun(@plus,sum(A.^2,2),sum(B.^2,2)’) – 2*(A*B’) ); It is based on the fact that: ||u-v||^2 = ||u||^2 + ||v||^2 – 2*u.v Consider below a crude comparison between the two methods: … Read more

Sort a matrix with another matrix

A somewhat clearer way to do this is to use a loop A = rand(3,4); B = rand(3,4); [sortedA,ind] = sort(A,2); for r = 1:size(A,1) B(r,:) = B(r,ind(r,:)); end Interestingly, the loop version is faster for small (<12 rows) and large (>~700 rows) square arrays (r2010a, OS X). The more columns there are relative to … Read more

In MATLAB, when is it optimal to use bsxfun?

There are three reasons I use bsxfun (documentation, blog link) bsxfun is faster than repmat (see below) bsxfun requires less typing Using bsxfun, like using accumarray, makes me feel good about my understanding of MATLAB. bsxfun will replicate the input arrays along their “singleton dimensions”, i.e., the dimensions along which the size of the array … Read more