Reputation: 6968
How do I extract the first ncolumns from a matrix, or how do i extract the columns from say, column 5 to column 5+n ?
The scenario is that I have a matrix, of dim=(i,j), then I want to look a contiguous blocks of column of length n. So I want to look at the matrix from column0 to column n, then at column1 to column n+1. etc. Until I reach the end of my matrix.
Thanks
>>> mat=array(range(0,20)).reshape(2,10)
>>> mat
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])
Given n=8. I want to extract the first 8 columns.
Then the matrix from column [1,11] to column [8,18]
Then the matrix from column [2,12] to column [9,19]
Upvotes: 2
Views: 6465
Reputation: 880797
Building on Sven Marnach's answer, if you want to perform a calculation on mat[:,0:8]
, then on mat[:,1:9]
, etc, you might be able to perform all the calculations "at once" on the 3-dimensional matrix
In [119]: x = np.lib.stride_tricks.as_strided(mat, shape = (3,2,8), strides = mat.itemsize*np.array([1,mat.shape[-1],1]))
In [120]: x
Out[120]:
array([[[ 0, 1, 2, 3, 4, 5, 6, 7],
[10, 11, 12, 13, 14, 15, 16, 17]],
[[ 1, 2, 3, 4, 5, 6, 7, 8],
[11, 12, 13, 14, 15, 16, 17, 18]],
[[ 2, 3, 4, 5, 6, 7, 8, 9],
[12, 13, 14, 15, 16, 17, 18, 19]]])
For example, to find the inner product of the rows, you could compute all three with
In [127]: np.sum(x[:,0,:]*x[:,1,:],axis = -1)
Out[127]: array([420, 564, 724])
instead of using a Python loop:
In [128]: for i in range(3):
.....: print(np.sum(mat[0,i:i+8]*mat[1,i:i+8]))
.....:
.....:
420
564
724
Upvotes: 3
Reputation: 602635
>>> mat[:, 0:8]
array([[ 0, 1, 2, 3, 4, 5, 6, 7],
[10, 11, 12, 13, 14, 15, 16, 17]])
>>> mat[:, 1:9]
array([[ 1, 2, 3, 4, 5, 6, 7, 8],
[11, 12, 13, 14, 15, 16, 17, 18]])
Upvotes: 4