Accessing and changing the shape

The number of dimensions is what distinguishes a vector from a matrix. The shape is what distinguishes vectors of different sizes, or matrices of different sizes. In this section, we examine how to obtain and change the shape of an array.

The shape function

The shape of a matrix is the tuple of its dimensions. The shape of an n × m matrix is the tuple (n, m). It can be obtained by the shape function:

M = identity(3)
shape(M) # (3, 3)

For a vector, the shape is a singleton containing the length of that vector:

v = array([1., 2., 1., 4.])
shape(v) # (4,) <- singleton (1-tuple)

An alternative is to use the array attribute shape, which gives  the same result:

M = array([[1.,2.]])
shape(M) # (1,2)
M.shape # (1,2)

However, the ...

Get Scientific Computing with Python 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.