开发者

Just curious about result from NumPy function!

I have used NumPy for my Master thesis. I've converted parts of the code from MATLAB code, but I have doubts in NumPy/Pyt开发者_如何学JAVAhon when I reference:

m = numpy.ones((10,2))
m[:,0]

which returns:

array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])

and when I ref to:

m[:,0:1]

it returns:

array([[ 1.],
       [ 1.],
       [ 1.],
       [ 1.],
       [ 1.],
       [ 1.],
       [ 1.],
       [ 1.],
       [ 1.],
       [ 1.]])

that I think it should be, cause same result with MATLAB!!!


This is because numpy has the concept of 1d arrays which Matlab doesn't have. Coupled with numpys broadcasting this provides a powerful simplification (less worrying about inserting transposes everywhere) but does mean you have to think a little bit about translating from Matlab. In this case, extracting a single column with a scalar Numpy simplifies the result to a 1d array - but with a slice it preserves the original dimensions. If you want to stay closer to Matlab semantics you could try using the Matrix class. See NumPy for matlab users page for details. In this case, you could do either of the following:

m[:,0][:,newaxis] # gives same as matlab
np.matrix(m)[:,0] # gives same as matlab

But remember if you use matrix class * becomes matrix multiplication and you need to use multiply() for elementwise. (This is all covered in NumPy for Matlab Users page). Generally I would recommend trying to get used to using 1d arrays where you would have column or row vector in matlab and generally things just work. You only need to worry about column vs row when reassembling them into a 2d array.

You may be interested in automated matlab to python converters such as OMPC (paper) (I think there are others as well).


I'm still learning Python myself, but I think the way that slicing works is that indices point to in-between locations, therefore 0:1 only gets you the first column. Is this what you were asking about?

This is what the documentation has to say:

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:

 +---+---+---+---+---+
 | H | e | l | p | A |
 +---+---+---+---+---+
 0   1   2   3   4   5
-5  -4  -3  -2  -1


I forget what numpy does, but Matlab indexes vectors from 1, not 0. So array(:,0) is an error in Matlab.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜