Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse diagonal on numpy python

Tags:

python

numpy

let's say I have this: (numpy array)

a=
[0  1  2  3],
[4  5  6  7],
[8  9 10  11]

to get [1,1] which is 5 its diagonal is zero; according to numpy, a.diagonal(0)= [0,5,10]. How do I get the reverse or the right to left diagonal [2,5,8] for [1,1]? Is this possible? My original problem is an 8 by 8 (0:7).. I hope that helps

like image 613
MasterWizard Avatar asked Nov 23 '13 16:11

MasterWizard


2 Answers

Get a new array each row reversed.

>>> import numpy as np
>>> a = np.array([
...     [0, 1, 2, 3],
...     [4, 5, 6, 7],
...     [8, 9, 10, 11]
... ])
>>> a[:, ::-1]
array([[ 3,  2,  1,  0],
       [ 7,  6,  5,  4],
       [11, 10,  9,  8]])
>>> a[:, ::-1].diagonal(1)
array([2, 5, 8])

or using numpy.fliplr:

>>> np.fliplr(a).diagonal(1)
array([2, 5, 8])
like image 82
falsetru Avatar answered Nov 06 '22 04:11

falsetru


Flip the array upside-down and use the same:

np.flipud(a).diagonal(0)[::-1]
like image 5
wim Avatar answered Nov 06 '22 04:11

wim