# HG changeset patch
# User Jason Grout <jason-sage@creativetrax.com>
# Date 1271724882 18000
# Node ID 338637719747111e3f30c1f1c3a1dee84d0e9d12
# Parent 40d5603e67a9a1b7d729c1565b7c1f3b996527c4
#8719: Make matrices convert to numpy arrays using numpy.array()
diff -r 40d5603e67a9 -r 338637719747 sage/matrix/matrix1.pyx
|
a
|
b
|
|
| 447 | 447 | sage: import numpy |
| 448 | 448 | sage: sorted(numpy.typecodes.items()) |
| 449 | 449 | [('All', '?bhilqpBHILQPfdgFDGSUVO'), ('AllFloat', 'fdgFDG'), ('AllInteger', 'bBhHiIlLqQpP'), ('Character', 'c'), ('Complex', 'FDG'), ('Float', 'fdg'), ('Integer', 'bhilqp'), ('UnsignedInteger', 'BHILQP')] |
| | 450 | |
| | 451 | Alternatively, numpy automatically calls this function (via |
| | 452 | the magic :meth:`__array__` method) to convert Sage matrices |
| | 453 | to numpy arrays:: |
| | 454 | |
| | 455 | sage: import numpy |
| | 456 | sage: b=numpy.array(a); b |
| | 457 | array([[ 0, 1, 2, 3], |
| | 458 | [ 4, 5, 6, 7], |
| | 459 | [ 8, 9, 10, 11]]) |
| | 460 | sage: b.dtype |
| | 461 | dtype('int64') |
| | 462 | sage: b.shape |
| | 463 | (3, 4) |
| 450 | 464 | """ |
| 451 | 465 | import numpy |
| 452 | 466 | A = numpy.matrix(self.list(), dtype=dtype) |
| 453 | 467 | return numpy.resize(A,(self.nrows(), self.ncols())) |
| 454 | 468 | |
| | 469 | # Define the magic "__array__" function so that numpy.array(m) can convert |
| | 470 | # a matrix m to a numpy array. |
| | 471 | # See http://docs.scipy.org/doc/numpy/user/c-info.how-to-extend.html#converting-an-arbitrary-sequence-object |
| | 472 | __array__=numpy |
| 455 | 473 | |
| 456 | 474 | ################################################### |
| 457 | 475 | # Construction functions |
diff -r 40d5603e67a9 -r 338637719747 sage/matrix/matrix_double_dense.pyx
|
a
|
b
|
|
| 1410 | 1410 | array([[ 0., 1., 2.], |
| 1411 | 1411 | [ 3., 4., 5.]]) |
| 1412 | 1412 | |
| | 1413 | Alternatively, numpy automatically calls this function (via |
| | 1414 | the magic :meth:`__array__` method) to convert Sage matrices |
| | 1415 | to numpy arrays:: |
| | 1416 | |
| | 1417 | sage: import numpy |
| | 1418 | sage: m = matrix(RDF, 2, range(6)); m |
| | 1419 | [0.0 1.0 2.0] |
| | 1420 | [3.0 4.0 5.0] |
| | 1421 | sage: numpy.array(m) |
| | 1422 | array([[ 0., 1., 2.], |
| | 1423 | [ 3., 4., 5.]]) |
| | 1424 | sage: numpy.array(m).dtype |
| | 1425 | dtype('float64') |
| | 1426 | sage: m = matrix(CDF, 2, range(6)); m |
| | 1427 | [ 0 1.0 2.0] |
| | 1428 | [3.0 4.0 5.0] |
| | 1429 | sage: numpy.array(m) |
| | 1430 | array([[ 0.+0.j, 1.+0.j, 2.+0.j], |
| | 1431 | [ 3.+0.j, 4.+0.j, 5.+0.j]]) |
| | 1432 | sage: numpy.array(m).dtype |
| | 1433 | dtype('complex128') |
| | 1434 | |
| 1413 | 1435 | TESTS: |
| 1414 | 1436 | sage: m = matrix(RDF,0,5,[]); m |
| 1415 | 1437 | [] |