diagonal_matrix and numpy arrays

Skip to first unread message

Dan Drake

Dec 14, 2010, 7:18:34 AM12/14/10
to sage-...@googlegroups.com
diagonal_matrix() does not seem smart enough to deal with 1-dimensional
numpy arrays:

sage: s
array([ 7.10977223, 2.10977223])

Both values are numpy floats:

sage: [parent(_) for _ in s]
[<type 'numpy.float64'>, <type 'numpy.float64'>]

But diagonal_matrix() can't make sense of s:

sage: diagonal_matrix(s)
Traceback (most recent call last):
UnboundLocalError: local variable 'v' referenced before assignment

I tried specifying the ring:

sage: diagonal_matrix(RDF, s)
Traceback (most recent call last):
ValueError: Invalid matrix constructor. Type matrix? for help

I also tried making a list out of s:

sage: diagonal_matrix(RDF, list(s))
Traceback (most recent call last):
TypeError: unable to find a common ring for all elements

(That's an unusual error, since both elements coerce into Sage float
types with no problem.)

Finally I got it to work, by doing everything myself:

sage: diagonal_matrix([RDF(_) for _ in s])
[7.10977222865 0.0]
[ 0.0 2.10977222865]

The usual matrix() function deals with numpy arrays with no problem, so
I expected diagonal_matrix() to do so as well. Should diagonal_matrix()
"Just Work" when given numpy arrays?


--- Dan Drake
----- http://mathsci.kaist.ac.kr/~drake


David Roe

Dec 14, 2010, 11:27:07 AM12/14/10
to sage-...@googlegroups.com
Yep. It's just something that hasn't been implemented yet.

> Version: GnuPG v1.4.10 (GNU/Linux)
> FMoAnjkndsTtkkNhRAGioWzTlSkGQTpd
> =NybY

Rob Beezer

Jan 12, 2011, 5:03:19 PM1/12/11
to sage-devel
A patch at:


adds NumPy arrays as input to the diagonal_matrix() constructor.


Felix Lawrence

Jan 12, 2011, 11:44:20 PM1/12/11
to sage-devel
Should conversion from numpy arrays/matrices to lists and sage vectors/
matrices be implemented by a .sage() method on the numpy array/
matrix? This is more consistent with the behaviour interface objects.

diagonal_matrix(), matrix(), etc could then outsource the conversion
steps to .sage(), rather than the numpy-specific conversions being
separately implemented in each of the functions.

.sage() would behave like this:
sage: a = numpy.array([1,2,6.4], dtype='float')
sage: type(a[0])
<type 'numpy.float64'>
sage: a_s = a.sage()
sage: type(a_s)
<type 'list'>
sage: a_s[0].parent()
Real Field with 53 bits of precision

sage: m = numpy.matrix([[1.,3,],[4.,5.6]],dtype='float')
sage: m_s = m.sage()
sage: m_s.parent()
Full MatrixSpace of 2 by 2 dense matrices over Real Field with 53 bits
of precision

I don't know where .sage() would be defined though.
Reply all
Reply to author
0 new messages