Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy extract submatrix

Tags:

python

numpy

I'm pretty new in numpy and I am having a hard time understanding how to extract from a np.array a sub matrix with defined columns and rows:

Y = np.arange(16).reshape(4,4) 

If I want to extract columns/rows 0 and 3, I should have:

[[0 3]  [12 15]] 

I tried all the reshape functions...but cannot figure out how to do this. Any ideas?

like image 796
user1595929 Avatar asked Oct 03 '13 14:10

user1595929


People also ask

How do you find the submatrix of a matrix?

Algorithm. Step 1 − Create a DP matrix of size (n+1)*(n+1). Step 2 − For each element of the matrix, find the sum till the current index. Step 3 − For all indexes from 0 to n, find the sum of sub-matrix of size size*size.

How do you find the sub matrix of a matrix in python?

Dynamic programming can be used to solve this problem, Create an array dp[N + 1][N + 1] where dp[i][j] stores the sum of all the elements with row between 1 to i and column between 1 to j. Once the 2-D matrix is generated, now suppose we wish to find sum of square starting with (i, j) to (i + x, j + x).

Can you index a NumPy array?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.


2 Answers

Give np.ix_ a try:

Y[np.ix_([0,3],[0,3])] 

This returns your desired result:

In [25]: Y = np.arange(16).reshape(4,4) In [26]: Y[np.ix_([0,3],[0,3])] Out[26]: array([[ 0,  3],        [12, 15]]) 
like image 165
JoshAdel Avatar answered Sep 22 '22 02:09

JoshAdel


One solution is to index the rows/columns by slicing/striding. Here's an example where you are extracting every third column/row from the first to last columns (i.e. the first and fourth columns)

In [1]: import numpy as np In [2]: Y = np.arange(16).reshape(4, 4) In [3]: Y[0:4:3, 0:4:3] Out[1]: array([[ 0,  3],                [12, 15]]) 

This gives you the output you were looking for.

For more info, check out this page on indexing in NumPy.

like image 33
mdml Avatar answered Sep 24 '22 02:09

mdml