简体   繁体   English

Matlab至python转换矩阵运算

[英]Matlab to python conversion matrix operations

Hi I am trying to covert this distance formula for rectilinear distance from matlab to python. 嗨,我想隐瞒这个距离公式,以了解从Matlab到python的直线距离。 X1 and X2 are two matrices of two dimensional points and could be differing lengths. X1和X2是两个二维点的矩阵,长度可能不同。

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. 我认为我在python中最常遇到的问题是将那些矩阵附加到X1和X2,因为它们是np.arrays。

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: 匹配的numpy代码:

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 : 产生, 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. numpy自动广播,因此不需要ones()来扩展尺寸。 Instead I use None (same as np.newaxis ) to create new dimensions. 相反,我使用None (与np.newaxis相同)来创建新尺寸。 The difference is then 3D , which is then summed on the last axis. 然后,差异为3D ,然后在最后一个轴上求和。

I forgot how spoilt we are with the numpy broadcasting . 我忘了numpy broadcasting对我们有多糟。 Though newer Octave has something similar: 尽管较新的Octave具有类似的功能:

D = sum(abs(reshape(X1,[],1,2)-reshape(X2,1,[],2)),3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM