[python] How can I find the dimensions of a matrix in Python?

How can I find the dimensions of a matrix in Python. Len(A) returns only one variable.

Edit:

close = dataobj.get_data(timestamps, symbols, closefield)

Is (I assume) generating a matrix of integers (less likely strings). I need to find the size of that matrix, so I can run some tests without having to iterate through all of the elements. As far as the data type goes, I assume it's an array of arrays (or list of lists).

This question is related to python matrix

The answer is


The correct answer is the following:

import numpy 
numpy.shape(a)

As Ayman farhat mentioned you can use the simple method len(matrix) to get the length of rows and get the length of the first row to get the no. of columns using len(matrix[0]) :

>>> a=[[1,5,6,8],[1,2,5,9],[7,5,6,2]]
>>> len(a)
3
>>> len(a[0])
4

Also you can use a library that helps you with matrices "numpy":

>>> import numpy 
>>> numpy.shape(a)
(3,4)

If you are using NumPy arrays, shape can be used. For example

  >>> a = numpy.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
  >>> a
  array([[[ 1,  2,  3],
         [ 1,  2,  3]],

         [[12,  3,  4],
         [ 2,  1,  3]]])
 >>> a.shape
 (2, 2, 3)

m = [[1, 1, 1, 0],[0, 5, 0, 1],[2, 1, 3, 10]]

print(len(m),len(m[0]))

Output

(3 4)


You simply can find a matrix dimension by using Numpy:

import numpy as np

x = np.arange(24).reshape((6, 4))
x.ndim

output will be:

2

It means this matrix is a 2 dimensional matrix.

x.shape

Will show you the size of each dimension. The shape for x is equal to:

(6, 4)

Suppose you have a which is an array. to get the dimensions of an array you should use shape.

import numpy as np a = np.array([[3,20,99],[-13,4.5,26],[0,-1,20],[5,78,-19]])
a.shape

The output of this will be (4,3)


To get just a correct number of dimensions in NumPy:

len(a.shape)

In the first case:

import numpy as np
a = np.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
print("shape = ",np.shape(a))
print("dimensions = ",len(a.shape))

The output will be:

shape =  (2, 2, 3)
dimensions =  3

You may use as following to get Height and Weight of an Numpy array:

int height = arr.shape[0]
int weight = arr.shape[1]

If your array has multiple dimensions, you can increase the index to access them.