2

I am working with a matrix, lets call it X, in python.

I know how to get the dimension of the matrix using X.shape but I am interested specially on using the number of rows of the matrix in a for loop, and I dont know how to get this value in a datatype suitable for a loop.

For example, imagine tihs simple situation:

a = np.matrix([[1,2,3],[4,5,6]])
for i in 1:(number of rows of a)
     print i

How can I get automatically that "number of rows of a"?

Two-Bit Alchemist
  • 17,966
  • 6
  • 47
  • 82
  • 1
    Possible duplicate of [Numpy array dimensions](http://stackoverflow.com/questions/3061761/numpy-array-dimensions) – miradulo Apr 20 '16 at 17:29

2 Answers2

2

X.shape[0] == number of rows in X

welch
  • 936
  • 8
  • 12
1

A superficial search on numpy will lead you to shape. It returns a tuple of array dimensions.

In your case, the first dimension (axe) concerns the columns. You can access it as you access a tuple's element:

import numpy as np

a = np.matrix([[1,2,3],[4,5,6]])
# a. shape[1]: columns
for i in range(0,a.shape[1]):
   print 'column '+format(i)

# a. shape[0]: rows   
for i in range(0, a.shape[0]):
   print 'row '+format(i)

This will print:

column 0
column 1
column 2
row 0
row 1
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130