Difference between numpy.array shape (R, 1) and (R,)

后端 未结 6 1545
甜味超标
甜味超标 2020-11-22 04:25

In numpy, some of the operations return in shape (R, 1) but some return (R,). This will make matrix multiplication more tedious since

6条回答
  •  孤独总比滥情好
    2020-11-22 04:48

    The difference between (R,) and (1,R) is literally the number of indices that you need to use. ones((1,R)) is a 2-D array that happens to have only one row. ones(R) is a vector. Generally if it doesn't make sense for the variable to have more than one row/column, you should be using a vector, not a matrix with a singleton dimension.

    For your specific case, there are a couple of options:

    1) Just make the second argument a vector. The following works fine:

        np.dot(M[:,0], np.ones(R))
    

    2) If you want matlab like matrix operations, use the class matrix instead of ndarray. All matricies are forced into being 2-D arrays, and operator * does matrix multiplication instead of element-wise (so you don't need dot). In my experience, this is more trouble that it is worth, but it may be nice if you are used to matlab.

提交回复
热议问题