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?
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.
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).
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.
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]])
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With