[Numpy-discussion] fixing diag() for matrices

Sven Schreiber svetosch at gmx.net
Tue Jul 25 12:20:00 CDT 2006

Robert Kern schrieb:
> Sven Schreiber wrote:
>> Hi,
>> there was a thread about this before, diag() is currently only
>> partly useful if you work with numpy-matrices, because the 1d->2d
>> direction doesn't work, as there are no 1d-numpy-matrices. This is
>> unfortunate because a numpy-matrix with shape (n,1) or (1,m) should be
>> naturally treated as a vector, imho. So it would be nice if this could
>> be fixed.
>> It's probably not the most efficient solution, but what I want for
>> numpy-matrix input x is to get:
>> mat(diag(x.A.squeeze))
>> where diag is the current implementation. This means that if x is not a
>> vector ("truly 2d"), then nothing is changed. But if one of the
>> dimensions of x is ==1, then it's turned into a 1d-array, and diag works
>> as it should.
>> Does that sound reasonable?
> Not for numpy.diag() in my opinion. However, I won't object to a 
> numpy.matlib.diag() that knows about matrix objects and behaves the way you want.

That would be fine with me. However, I'd like to point out that after
some bug-squashing currently all numpy functions deal with
numpy-matrices correctly, afaik. The current behavior of numpy.diag
could be viewed as a violation of that principle. (Because if x has
shape (n,1), diag(x) returns only the first entry, which is pretty
stupid for a diag-function operating on a vector.)  I repeat, the matlib
solution would be ok for me, but in some sense not fixing numpy.diag
could contribute to the feeling of matrices being only second-class


More information about the Numpy-discussion mailing list