[Tutor] extract a submatrix
Eike Welk
eike.welk at gmx.net
Mon Jul 12 12:03:22 CEST 2010
Hello Bala!
On Sunday July 11 2010 23:41:14 Bala subramanian wrote:
> I have a
> matrix of size 550,550. I want to extract only part of this matrix say
> first 330 elements, i dnt need the last 220 elements in the matrix. is
> there any function in numpy that can do this kind of extraction.
I demonstrate it with a integer matrix of dimension (5, 10):
In [3]: a = array(range(50)).reshape(5,10)
In [4]: a
Out[4]:
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]])
In [5]: a[:, 0:7]
Out[5]:
array([[ 0, 1, 2, 3, 4, 5, 6],
[10, 11, 12, 13, 14, 15, 16],
[20, 21, 22, 23, 24, 25, 26],
[30, 31, 32, 33, 34, 35, 36],
[40, 41, 42, 43, 44, 45, 46]])
In [6]: a[:, 7:]
Out[6]:
array([[ 7, 8, 9],
[17, 18, 19],
[27, 28, 29],
[37, 38, 39],
[47, 48, 49]])
The colons ":" denote slices. In a 2D array you can have slices in two
dimensions. in the first dimension (downwards) I always select all elements.
A good explanation of slices is here:
http://tiny.cc/ohl2g
http://stackoverflow.com/questions/509211/good-primer-for-python-slice-
notation
A nice list of Numpy's many functions and methods is here: (This is the Numpy
page I use most often.)
http://tiny.cc/qzwoq
http://www.scipy.org/Numpy_Example_List_With_Doc#head-11717acafb821da646a8db6997e59b820ac8761a
The funny prompt is from IPython (ipython --pylab), a program that enhances
Python's interactive mode, and keeps Matplotlib graphs alive.
Eike.
More information about the Tutor
mailing list