4

What is the difference between

numpy.zeros(n)

and

numpy.zeros(n,1)?

The output for the first statement is

[0 0 ..... n times]

whereas the second one is

([0] [0]

.... n rows)

  • 1
    I get an error with `numpy.zeros(n, 1)`. I'm guessing you meant `numpy.zeros((n,1))`. – Gabe Hackebeil Oct 22 '16 at 04:41
  • 1
    for a detailed description of the difference between `(n,)` shape and `(n,1)` look at http://stackoverflow.com/questions/22053050/difference-between-numpy-array-shape-r-1-and-r (and other such questions). – hpaulj Oct 22 '16 at 06:41
  • @hpaulj: I'd go as far as saying that's a perfect candidate for a question to close this as a dupe of – Eric Oct 22 '16 at 12:04

1 Answers1

3

The first argument indicates the shape of the array. A scalar argument implies a "flat" array (vector), whereas a tuple argument is interpreted as the dimensions of a tensor. So if the argument is the tuple (m,n), numpy.zeros will return a matrix with m rows and n columns. In your case, it is returning a matrix with n rows and 1 column.

Although your two cases are equivalent in some sense, linear algebra routines that require a vector as input will likely expect something like the first form.

Gabe Hackebeil
  • 1,376
  • 1
  • 8
  • 10
  • numpy treats 1-D matrices (n,) differently than 2-D matrices with a singleton dimension (n, 1). – TWReever Oct 22 '16 at 04:59
  • @TWReever: Thanks for clarifying my last statement. – Gabe Hackebeil Oct 22 '16 at 05:20
  • definitely takes some getting used to, especially if used to the more conventional way they're treated, like in Matlab. – TWReever Oct 22 '16 at 05:25
  • MATLAB still has fossils from the days when its only data structure was a 2d matrix. `numpy` lives in world with scalars and lists. Its arrays can have any number of dimensions - 0,1,2.... – hpaulj Oct 22 '16 at 05:36