Selective Grab Rows of Matrix Numpy

Selective Grab Rows of Matrix Numpy



Is there a way to index a 3D numpy matrix to selectively grab the ith row of each layer?



e.g. I have an RxNxR matrix, and I want to grab the 1st row of the 1st layer, the 2nd row of the 2nd layer, the 3rd row of the 3rd layer, etc. and end up with an RxN matrix.



Can I do that in a single operation?




3 Answers
3



Using the numpy.diagonal function:


a = np.arange(27).reshape(3, 3, 3)
np.diagonal(a, offset=0, axis1=0, axis2=1).T



gives


array([[ 0, 1, 2],
[12, 13, 14],
[24, 25, 26]])





can this possibly be generalized to also work with the case where R = 1? say I have a 1x3x1 matrix, this command is giving me only the first element, not the full row.
– Vivek Sridhar
Aug 23 at 15:16





It works if the matrix is 3x1x1... Which dimension corresponds to the layers? or you can try np.diagonal(a, offset=0, axis1=0, axis2=2)
– xdze2
Aug 23 at 15:22


np.diagonal(a, offset=0, axis1=0, axis2=2)





That did the trick! (the layers are the third dimension). Thanks!
– Vivek Sridhar
Aug 23 at 15:29



I believe this should do the trick:


import numpy as np
matrix = ...
result = np.zeros((matrix.shape[0], matrix.shape[1]))

for i in range(0, len(matrix)):
result[i] = matrix[i][i]



I think you could use a comprehension - depends on which dimensions you define as your 'layer', etc but this would work:


a = np.array([...])

[a[:, i, 0] for i in range(np.shape(a)[1])]






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế