将一段代码从matlab改为python, 总是出来的结果与之前matlab的结果相去甚远, 接着尝试各种方法的结果是否一致,
最后将信将疑的试了reshape, 结果声泪俱下, 真的是这个函数, google一下……
MATLAB
>> mat = [1:12]
mat =
1 2 3 4 5 6 7 8 9 10 11 12
>> reshape(mat,[3,4])
ans =
1 4 7 10
2 5 8 11
3 6 9 12
PYTHON
mat = np.arange(1,13)
mat
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
r = np.reshape(mat,(3,4))
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
r.shape
(3, 4)
相同的代码matlab 与python出现了不同的排布方式.
PYTHON修正代码
r = np.reshape(mat, (3,4), order="F")
r
array([[ 1, 4, 7, 10],
[ 2, 5, 8, 11],
[ 3, 6, 9, 12]])
解释
需要在python程序中指明使用Fortran order, 如
np.reshape(matrix, (n,n), order="F")