0

Hi I am trying to covert this distance formula for rectilinear distance from matlab to python. X1 and X2 are two matrices of two dimensional points and could be differing lengths.

nd = size(X1); n = nd(1); 
d = nd(2);  
m = size(X2,1);

D = abs(X1(:,ones(1,m)) - X2(:,ones(1,n))') + ...
     abs(X1(:,2*ones(1,m)) - X2(:,2*ones(1,n))');

I think the problem I am having most in python is appending the ones matrices with X1 and X2 since they are np.arrays.

4
  • Do you need the Python version of the code? Commented May 2, 2014 at 4:55
  • Yes, I need the Python version. Commented May 2, 2014 at 4:56
  • This helps : mathesaurus.sourceforge.net/matlab-numpy.html Commented May 2, 2014 at 4:58
  • 'appending the ones matrices with X1 and X2' doesn't sound right. You are indexing X1 and X2 with the ones. Commented May 2, 2014 at 5:36

1 Answer 1

1

First your code:

octave:1> X1=[0,1,2,3;2,3,1,1]'
octave:2> X2=[2,3,2;4,2,4]'
<your code>
octave:21> D
D =
   4   3   4
   2   3   2
   3   2   3
   4   1   4

Matching numpy code:

X1=np.array([[0,1,2,3],[2,3,1,1]]).T
X2=np.array([[2,3,2],[4,2,4]]).T
D=np.abs(X1[:,None,:]-X2[None,:,:]).sum(axis=-1)

produces, D:

array([[4, 3, 4],
       [2, 3, 2],
       [3, 2, 3],
       [4, 1, 4]])

numpy broadcasts automatically, so it doesn't need the ones() to expand the dimensions. Instead I use None (same as np.newaxis) to create new dimensions. The difference is then 3D, which is then summed on the last axis.

I forgot how spoilt we are with the numpy broadcasting. Though newer Octave has something similar:

D = sum(abs(reshape(X1,[],1,2)-reshape(X2,1,[],2)),3)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.