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
18.6k6 gold badges52 silver badges85 bronze badges
asked Apr 20, 2016 at 17:28
1

2 Answers 2

2

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

answered Apr 20, 2016 at 17:57
Sign up to request clarification or add additional context in comments.

Comments

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
answered Apr 20, 2016 at 18:00

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.