48

Is there an equivalent to the MATLAB size() command in Numpy?

In MATLAB,

>>> a = zeros(2,5)
 0 0 0 0 0
 0 0 0 0 0
>>> size(a)
 2 5

In Python,

>>> a = zeros((2,5))
>>> a
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
>>> ?????
5
  • 2
    Have a look at one of many such pages: scipy.org/NumPy_for_Matlab_Users Commented Jun 22, 2012 at 14:19
  • I'm really curious why shape is an attribute of arrays and a function in the numpy model but not a method of array objects. Is there an obvious answer? Does it feel like it merits a separate SO question, or is it too potentially opinion-based? Commented Feb 25, 2015 at 18:13
  • Here is the updated NumPy for Matlab Users link. Commented Mar 14, 2019 at 18:25
  • @BenBolker It's because it's setable. For example in this case, a.shape = (10,) Commented Jan 10, 2023 at 20:38
  • 1
    I ended up asking this question here: stackoverflow.com/questions/28726674/… Commented Jan 10, 2023 at 20:45

3 Answers 3

73

This is called the "shape" in NumPy, and can be requested via the .shape attribute:

>>> a = zeros((2, 5))
>>> a.shape
(2, 5)

If you prefer a function, you could also use numpy.shape(a).

Sign up to request clarification or add additional context in comments.

2 Comments

We can switch freely between np.method(x) and x.method when x is a numpy object?
@Guimoute It depends. First, shape isn't a method, it's a property. And for many methods there are corresponding module-level functions, but not for all of them. You need to consult the documentation for details.
14

Yes numpy has a size function, and shape and size are not quite the same.

Input

import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)

print(data)
print(arrData.size)
print(arrData.shape)

Output

[[1, 2, 3, 4], [5, 6, 7, 8]]

8 # size

(2, 4) # shape

Comments

2

[w,k] = a.shape will give you access to individual sizes if you want to use it for loops like in matlab

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.