Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagesmc
Path: blob/master/src/sage/matrix/matrix1.pyx
8815 views
1
"""
2
Base class for matrices, part 1
3
4
For design documentation see :mod:`sage.matrix.docs`.
5
6
TESTS::
7
8
sage: A = Matrix(GF(5),3,3,srange(9))
9
sage: TestSuite(A).run()
10
"""
11
12
################################################################################
13
# Copyright (C) 2005, 2006 William Stein <[email protected]>
14
#
15
# Distributed under the terms of the GNU General Public License (GPL).
16
# The full text of the GPL is available at:
17
#
18
# http://www.gnu.org/licenses/
19
################################################################################
20
21
include "sage/ext/stdsage.pxi"
22
include "sage/ext/python.pxi"
23
24
import sage.modules.free_module
25
26
cdef class Matrix(matrix0.Matrix):
27
###################################################
28
# Coercion to Various Systems
29
###################################################
30
31
def _pari_init_(self):
32
"""
33
Return a string defining a GP representation of self.
34
35
EXAMPLES::
36
37
sage: R.<x> = QQ['x']
38
sage: a = matrix(R,2,[x+1,2/3, x^2/2, 1+x^3]); a
39
[ x + 1 2/3]
40
[1/2*x^2 x^3 + 1]
41
sage: b = gp(a); b # indirect doctest
42
[x + 1, 2/3; 1/2*x^2, x^3 + 1]
43
sage: a.determinant()
44
x^4 + x^3 - 1/3*x^2 + x + 1
45
sage: b.matdet()
46
x^4 + x^3 - 1/3*x^2 + x + 1
47
"""
48
w = self.list()
49
cdef Py_ssize_t nr, nc, i, j
50
nr = self._nrows
51
nc = self._ncols
52
v = []
53
for i from 0 <= i < nr:
54
tmp = []
55
for j from 0 <= j < nc:
56
tmp.append(w[i*nc + j]._pari_init_())
57
v.append( ','.join(tmp))
58
return 'Mat([%s])'%(';'.join(v))
59
60
def _pari_(self):
61
"""
62
Return the Pari matrix corresponding to self.
63
64
EXAMPLES::
65
66
sage: R.<x> = QQ['x']
67
sage: a = matrix(R,2,[x+1,2/3, x^2/2, 1+x^3]); a
68
[ x + 1 2/3]
69
[1/2*x^2 x^3 + 1]
70
sage: b = pari(a); b # indirect doctest
71
[x + 1, 2/3; 1/2*x^2, x^3 + 1]
72
sage: a.determinant()
73
x^4 + x^3 - 1/3*x^2 + x + 1
74
sage: b.matdet()
75
x^4 + x^3 - 1/3*x^2 + x + 1
76
77
This function preserves precision for entries of inexact type (e.g.
78
reals)::
79
80
sage: R = RealField(4) # 4 bits of precision
81
sage: a = matrix(R, 2, [1, 2, 3, 1]); a
82
[1.0 2.0]
83
[3.0 1.0]
84
sage: b = pari(a); b
85
[1.000000000, 2.000000000; 3.000000000, 1.000000000] # 32-bit
86
[1.00000000000000, 2.00000000000000; 3.00000000000000, 1.00000000000000] # 64-bit
87
sage: b[0][0].precision() # in words
88
3
89
"""
90
from sage.libs.pari.all import pari
91
return pari.matrix(self._nrows, self._ncols, self._list())
92
93
def _gap_init_(self):
94
"""
95
Returns a string defining a gap representation of self.
96
97
EXAMPLES::
98
99
sage: A = MatrixSpace(QQ,3,3)([0,1,2,3,4,5,6,7,8])
100
sage: g = gap(A) # indirect doctest
101
sage: g
102
[ [ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ] ]
103
sage: g.CharacteristicPolynomial()
104
x_1^3-12*x_1^2-18*x_1
105
sage: A.characteristic_polynomial()
106
x^3 - 12*x^2 - 18*x
107
sage: matrix(g,QQ) == A
108
True
109
110
Particularly difficult is the case of matrices over
111
cyclotomic fields and general number fields. See
112
tickets #5618 and #8909.
113
::
114
115
sage: K.<zeta> = CyclotomicField(8)
116
sage: A = MatrixSpace(K,2,2)([0,1+zeta,2*zeta,3])
117
sage: g = gap(A); g
118
[ [ 0, 1+E(8) ], [ 2*E(8), 3 ] ]
119
sage: matrix(g,K) == A
120
True
121
sage: g.IsMatrix()
122
true
123
124
sage: L.<tau> = NumberField(x^3-2)
125
sage: A = MatrixSpace(L,2,2)([0,1+tau,2*tau,3])
126
sage: g = gap(A); g
127
[ [ !0, tau+1 ], [ 2*tau, !3 ] ]
128
sage: matrix(g,L) == A
129
True
130
131
"""
132
cdef Py_ssize_t i, j
133
v = []
134
for i from 0 <= i < self._nrows:
135
tmp = []
136
for j from 0 <= j < self._ncols:
137
tmp.append(self.get_unsafe(i,j)._gap_init_())
138
v.append( '[%s]'%(','.join(tmp)) )
139
# It is needed to multiply with 'One(...)', because
140
# otherwise the result would not be a gap matrix
141
return '[%s]*One(%s)'%(','.join(v),sage.interfaces.gap.gap(self.base_ring()).name())
142
143
def _libgap_(self):
144
"""
145
Construct a LibGAP matrix.
146
147
INPUT:
148
149
- ``M`` -- a matrix.
150
151
OUTPUT:
152
153
A GAP matrix, that is, a list of lists with entries over a
154
common ring.
155
156
EXAMPLES::
157
158
sage: libgap(identity_matrix(ZZ,2))
159
[ [ 1, 0 ], [ 0, 1 ] ]
160
sage: libgap(matrix(GF(3),2,2,[4,5,6,7]))
161
[ [ Z(3)^0, Z(3) ], [ 0*Z(3), Z(3)^0 ] ]
162
"""
163
from sage.libs.gap.libgap import libgap
164
return libgap._construct_matrix(self)
165
166
def _giac_init_(self):
167
"""
168
Return a Giac string representation of this matrix.
169
170
EXAMPLES::
171
172
sage: M = matrix(ZZ,2,range(4)) #optional
173
sage: giac(M) #optional (indirect doctest)
174
[[0,1],[2,3]]
175
176
::
177
178
sage: M = matrix(QQ,3,[1,2,3,4/3,5/3,6/4,7,8,9]) #optional
179
sage: giac(M) #optional
180
[[1,2,3],[4/3,5/3,3/2],[7,8,9]]
181
182
::
183
184
sage: P.<x> = ZZ[] #optional
185
sage: M = matrix(P, 2, [-9*x^2-2*x+2, x-1, x^2+8*x, -3*x^2+5]) #optional
186
sage: giac(M) #optional
187
[[-9*x^2-2*x+2,x-1],[x^2+8*x,-3*x^2+5]]
188
"""
189
s = str(self.rows()).replace('(','[').replace(')',']')
190
return "(%s)"%(s)
191
192
def _maxima_init_(self):
193
"""
194
Return a string representation of this matrix in Maxima.
195
196
EXAMPLES::
197
198
sage: m = matrix(3,range(9)); m
199
[0 1 2]
200
[3 4 5]
201
[6 7 8]
202
sage: m._maxima_init_()
203
'matrix([0,1,2],[3,4,5],[6,7,8])'
204
sage: a = maxima(m); a
205
matrix([0,1,2],[3,4,5],[6,7,8])
206
sage: a.charpoly('x').expand()
207
-x^3+12*x^2+18*x
208
sage: m.charpoly()
209
x^3 - 12*x^2 - 18*x
210
"""
211
cdef Py_ssize_t i, j
212
v = []
213
for i from 0 <= i < self._nrows:
214
tmp = []
215
for j from 0 <= j < self._ncols:
216
tmp.append(self.get_unsafe(i,j)._maxima_init_())
217
v.append( '[%s]'%(','.join(tmp)) )
218
return 'matrix(%s)'%(','.join(v))
219
220
def _mathematica_init_(self):
221
"""
222
Return Mathematica string representation of this matrix.
223
224
EXAMPLES::
225
226
sage: A = MatrixSpace(QQ,3)([1,2,3,4/3,5/3,6/4,7,8,9])
227
sage: g = mathematica(A); g # optional
228
{{1, 2, 3}, {4/3, 5/3, 3/2}, {7, 8, 9}}
229
sage: A._mathematica_init_()
230
'{{1/1, 2/1, 3/1}, {4/3, 5/3, 3/2}, {7/1, 8/1, 9/1}}'
231
232
::
233
234
sage: A = matrix([[1,2],[3,4]])
235
sage: g = mathematica(A); g # optional
236
{{1, 2}, {3, 4}}
237
238
::
239
240
sage: a = matrix([[pi, sin(x)], [cos(x), 1/e]]); a
241
[ pi sin(x)]
242
[cos(x) e^(-1)]
243
sage: a._mathematica_init_()
244
'{{Pi, Sin[x]}, {Cos[x], Exp[-1]}}'
245
"""
246
return '{' + ', '.join([v._mathematica_init_() for v in self.rows()]) + '}'
247
248
def _magma_init_(self, magma):
249
r"""
250
Return a string that evaluates in the given Magma session to this
251
matrix.
252
253
EXAMPLES:
254
255
We first coerce a square matrix.
256
257
::
258
259
sage: A = MatrixSpace(QQ,3)([1,2,3,4/3,5/3,6/4,7,8,9])
260
sage: B = magma(A); B # (indirect doctest) optional - magma
261
[ 1 2 3]
262
[4/3 5/3 3/2]
263
[ 7 8 9]
264
sage: B.Type() # optional - magma
265
AlgMatElt
266
sage: B.Parent() # optional - magma
267
Full Matrix Algebra of degree 3 over Rational Field
268
269
We coerce a non-square matrix over
270
`\ZZ/8\ZZ`.
271
272
::
273
274
sage: A = MatrixSpace(Integers(8),2,3)([-1,2,3,4,4,-2])
275
sage: B = magma(A); B # optional - magma
276
[7 2 3]
277
[4 4 6]
278
sage: B.Type() # optional - magma
279
ModMatRngElt
280
sage: B.Parent() # optional - magma
281
Full RMatrixSpace of 2 by 3 matrices over IntegerRing(8)
282
283
::
284
285
sage: R.<x,y> = QQ[]
286
sage: A = MatrixSpace(R,2,2)([x+y,x-1,y+5,x*y])
287
sage: B = magma(A); B # optional - magma
288
[x + y x - 1]
289
[y + 5 x*y]
290
291
::
292
293
sage: R.<x,y> = ZZ[]
294
sage: A = MatrixSpace(R,2,2)([x+y,x-1,y+5,x*y])
295
sage: B = magma(A); B # optional - magma
296
[x + y x - 1]
297
[y + 5 x*y]
298
299
We coerce a matrix over a cyclotomic field, where the generator
300
must be named during the coercion.
301
302
::
303
304
sage: K = CyclotomicField(9) ; z = K.0
305
sage: M = matrix(K,3,3,[0,1,3,z,z**4,z-1,z**17,1,0])
306
sage: M
307
[ 0 1 3]
308
[ zeta9 zeta9^4 zeta9 - 1]
309
[-zeta9^5 - zeta9^2 1 0]
310
sage: magma(M) # optional - magma
311
[ 0 1 3]
312
[ zeta9 zeta9^4 zeta9 - 1]
313
[-zeta9^5 - zeta9^2 1 0]
314
sage: magma(M**2) == magma(M)**2 # optional - magma
315
True
316
"""
317
P = magma(self.parent())
318
v = [x._magma_init_(magma) for x in self.list()]
319
return '%s![%s]'%(P.name(), ','.join(v))
320
321
def _maple_init_(self):
322
"""
323
Return a Maple string representation of this matrix.
324
325
EXAMPLES::
326
327
sage: M = matrix(ZZ,2,range(4)) #optional
328
sage: maple(M) #optional (indirect doctest)
329
Matrix(2, 2, [[0,1],[2,3]])
330
331
::
332
333
sage: M = matrix(QQ,3,[1,2,3,4/3,5/3,6/4,7,8,9]) #optional
334
sage: maple(M) #optional
335
Matrix(3, 3, [[1,2,3],[4/3,5/3,3/2],[7,8,9]])
336
337
::
338
339
sage: P.<x> = ZZ[] #optional
340
sage: M = matrix(P, 2, [-9*x^2-2*x+2, x-1, x^2+8*x, -3*x^2+5]) #optional
341
sage: maple(M) #optional
342
Matrix(2, 2, [[-9*x^2-2*x+2,x-1],[x^2+8*x,-3*x^2+5]])
343
"""
344
s = str(self.rows()).replace('(','[').replace(')',']')
345
return "Matrix(%s,%s,%s)"%(self.nrows(), self.ncols(), s)
346
347
def _singular_(self, singular=None):
348
"""
349
Tries to coerce this matrix to a singular matrix.
350
"""
351
if singular is None:
352
from sage.interfaces.all import singular as singular_default
353
singular = singular_default
354
try:
355
self.base_ring()._singular_(singular)
356
except (NotImplementedError, AttributeError):
357
raise TypeError, "Cannot coerce to Singular"
358
359
return singular.matrix(self.nrows(),self.ncols(),singular(self.list()))
360
361
def _macaulay2_(self, macaulay2=None):
362
"""
363
EXAMPLES::
364
365
sage: m = matrix(ZZ, [[1,2],[3,4]])
366
sage: macaulay2(m) #optional (indirect doctest)
367
| 1 2 |
368
| 3 4 |
369
370
::
371
372
sage: R.<x,y> = QQ[]
373
sage: m = matrix([[x,y],[1+x,1+y]])
374
sage: macaulay2(m) #optional
375
| x y |
376
| x+1 y+1 |
377
"""
378
base_ring = macaulay2(self.base_ring())
379
entries = map(list, self)
380
return macaulay2(entries).matrix()
381
382
383
def _scilab_init_(self):
384
"""
385
Returns a string defining a Scilab representation of self.
386
387
EXAMPLES:
388
389
sage: a = matrix([[1,2,3],[4,5,6],[7,8,9]]); a # optional - scilab
390
[1 2 3]
391
[4 5 6]
392
[7 8 9]
393
sage: a._scilab_init_() # optional - scilab
394
'[1,2,3;4,5,6;7,8,9]'
395
396
AUTHORS:
397
398
- Ronan Paixao (2008-12-12)
399
"""
400
w = self.list()
401
cdef Py_ssize_t nr, nc, i, j
402
nr = self._nrows
403
nc = self._ncols
404
v = []
405
for i from 0 <= i < nr:
406
tmp = []
407
for j from 0 <= j < nc:
408
tmp.append(w[i*nc + j]._pari_init_())
409
v.append( ','.join(tmp))
410
return '[%s]'%(';'.join(v))
411
412
def _scilab_(self, scilab=None):
413
"""
414
Creates a ScilabElement object based on self and returns it.
415
416
EXAMPLES:
417
418
sage: a = matrix([[1,2,3],[4,5,6],[7,8,9]]); a # optional - scilab
419
[1 2 3]
420
[4 5 6]
421
[7 8 9]
422
sage: b = scilab(a); b # optional - scilab (indirect doctest)
423
1. 2. 3.
424
4. 5. 6.
425
7. 8. 9.
426
427
AUTHORS:
428
429
- Ronan Paixao (2008-12-12)
430
"""
431
return scilab(self._scilab_init_())
432
433
434
def _sage_input_(self, sib, coerce):
435
r"""
436
Produce an expression which will reproduce this value when evaluated.
437
438
EXAMPLES::
439
440
sage: sage_input(matrix(QQ, 3, 3, [5..13])/7, verify=True)
441
# Verified
442
matrix(QQ, [[5/7, 6/7, 1], [8/7, 9/7, 10/7], [11/7, 12/7, 13/7]])
443
sage: sage_input(MatrixSpace(GF(5), 50, 50, sparse=True).random_element(density=0.002), verify=True)
444
# Verified
445
matrix(GF(5), 50, 50, {(4,44):2, (5,25):1, (26,9):3, (43,24):3, (44,38):4})
446
sage: from sage.misc.sage_input import SageInputBuilder
447
sage: matrix(RDF, [[3, 1], [4, 1]])._sage_input_(SageInputBuilder(), False)
448
{call: {atomic:matrix}({atomic:RDF}, {list: ({list: ({atomic:3}, {atomic:1})}, {list: ({atomic:4}, {atomic:1})})})}
449
sage: matrix(ZZ, 50, 50, {(9,17):1})._sage_input_(SageInputBuilder(), False)
450
{call: {atomic:matrix}({atomic:ZZ}, {atomic:50}, {atomic:50}, {dict: {{atomic:(9,17)}:{atomic:1}}})}
451
452
TESTS::
453
454
sage: sage_input(matrix(RR, 0, 3, []), verify=True)
455
# Verified
456
matrix(RR, 0, 3)
457
sage: sage_input(matrix(RR, 3, 0, []), verify=True)
458
# Verified
459
matrix(RR, 3, 0)
460
sage: sage_input(matrix(RR, 0, 0, []), verify=True)
461
# Verified
462
matrix(RR, 0, 0)
463
"""
464
if self.is_sparse():
465
entries = list(self.dict().items())
466
entries.sort()
467
# We hand-format the keys to get rid of the space that would
468
# normally follow the comma
469
entries = [(sib.name('(%d,%d)'%k), sib(v, 2)) for k,v in entries]
470
return sib.name('matrix')(self.base_ring(),
471
sib.int(self.nrows()),
472
sib.int(self.ncols()),
473
sib.dict(entries))
474
elif self.nrows() == 0 or self.ncols() == 0:
475
return sib.name('matrix')(self.base_ring(),
476
sib.int(self.nrows()),
477
sib.int(self.ncols()))
478
else:
479
entries = [[sib(v, 2) for v in row] for row in self.rows()]
480
return sib.name('matrix')(self.base_ring(), entries)
481
482
483
def numpy(self, dtype=None):
484
"""
485
Return the Numpy matrix associated to this matrix.
486
487
INPUT:
488
489
- ``dtype`` - The desired data-type for the array. If not given,
490
then the type will be determined as the minimum type required
491
to hold the objects in the sequence.
492
493
EXAMPLES::
494
495
sage: a = matrix(3,range(12))
496
sage: a.numpy()
497
array([[ 0, 1, 2, 3],
498
[ 4, 5, 6, 7],
499
[ 8, 9, 10, 11]])
500
sage: a.numpy('f')
501
array([[ 0., 1., 2., 3.],
502
[ 4., 5., 6., 7.],
503
[ 8., 9., 10., 11.]], dtype=float32)
504
sage: a.numpy('d')
505
array([[ 0., 1., 2., 3.],
506
[ 4., 5., 6., 7.],
507
[ 8., 9., 10., 11.]])
508
sage: a.numpy('B')
509
array([[ 0, 1, 2, 3],
510
[ 4, 5, 6, 7],
511
[ 8, 9, 10, 11]], dtype=uint8)
512
513
Type ``numpy.typecodes`` for a list of the possible
514
typecodes::
515
516
sage: import numpy
517
sage: sorted(numpy.typecodes.items())
518
[('All', '?bhilqpBHILQPefdgFDGSUVOMm'), ('AllFloat', 'efdgFDG'), ('AllInteger', 'bBhHiIlLqQpP'), ('Character', 'c'), ('Complex', 'FDG'), ('Datetime', 'Mm'), ('Float', 'efdg'), ('Integer', 'bhilqp'), ('UnsignedInteger', 'BHILQP')]
519
520
Alternatively, numpy automatically calls this function (via
521
the magic :meth:`__array__` method) to convert Sage matrices
522
to numpy arrays::
523
524
sage: import numpy
525
sage: b=numpy.array(a); b
526
array([[ 0, 1, 2, 3],
527
[ 4, 5, 6, 7],
528
[ 8, 9, 10, 11]])
529
sage: b.dtype
530
dtype('int32') # 32-bit
531
dtype('int64') # 64-bit
532
sage: b.shape
533
(3, 4)
534
"""
535
import numpy
536
A = numpy.matrix(self.list(), dtype=dtype)
537
return numpy.resize(A,(self.nrows(), self.ncols()))
538
539
# Define the magic "__array__" function so that numpy.array(m) can convert
540
# a matrix m to a numpy array.
541
# See http://docs.scipy.org/doc/numpy/user/c-info.how-to-extend.html#converting-an-arbitrary-sequence-object
542
__array__=numpy
543
544
###################################################
545
# Construction functions
546
###################################################
547
548
def matrix_over_field(self):
549
"""
550
Return copy of this matrix, but with entries viewed as elements of
551
the fraction field of the base ring (assuming it is defined).
552
553
EXAMPLES::
554
555
sage: A = MatrixSpace(IntegerRing(),2)([1,2,3,4])
556
sage: B = A.matrix_over_field()
557
sage: B
558
[1 2]
559
[3 4]
560
sage: B.parent()
561
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
562
"""
563
return self.change_ring(self.base_ring().fraction_field())
564
565
566
def lift(self):
567
"""
568
Return lift of self to the covering ring of the base ring R,
569
which is by definition the ring returned by calling
570
cover_ring() on R, or just R itself if the cover_ring method
571
is not defined.
572
573
EXAMPLES::
574
575
sage: M = Matrix(Integers(7), 2, 2, [5, 9, 13, 15]) ; M
576
[5 2]
577
[6 1]
578
sage: M.lift()
579
[5 2]
580
[6 1]
581
sage: parent(M.lift())
582
Full MatrixSpace of 2 by 2 dense matrices over Integer Ring
583
584
The field QQ doesn't have a cover_ring method::
585
586
sage: hasattr(QQ, 'cover_ring')
587
False
588
589
So lifting a matrix over QQ gives back the same exact matrix.
590
591
::
592
593
sage: B = matrix(QQ, 2, [1..4])
594
sage: B.lift()
595
[1 2]
596
[3 4]
597
sage: B.lift() is B
598
True
599
"""
600
if hasattr(self._base_ring, 'cover_ring'):
601
S = self._base_ring.cover_ring()
602
if S is not self._base_ring:
603
return self.change_ring(S)
604
return self
605
606
#############################################################################################
607
# rows, columns, sparse_rows, sparse_columns, dense_rows, dense_columns, row, column
608
#############################################################################################
609
610
def columns(self, copy=True):
611
r"""
612
Return a list of the columns of self.
613
614
INPUT:
615
616
- ``copy`` - (default: True) if True, return a copy of the list
617
of columns which is safe to change.
618
619
If ``self`` is a sparse matrix, columns are returned as sparse vectors,
620
otherwise returned vectors are dense.
621
622
EXAMPLES::
623
624
sage: matrix(3, [1..9]).columns()
625
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
626
sage: matrix(RR, 2, [sqrt(2), pi, exp(1), 0]).columns()
627
[(1.41421356237310, 2.71828182845905), (3.14159265358979, 0.000000000000000)]
628
sage: matrix(RR, 0, 2, []).columns()
629
[(), ()]
630
sage: matrix(RR, 2, 0, []).columns()
631
[]
632
sage: m = matrix(RR, 3, 3, {(1,2): pi, (2, 2): -1, (0,1): sqrt(2)})
633
sage: parent(m.columns()[0])
634
Sparse vector space of dimension 3 over Real Field with 53 bits of precision
635
636
Sparse matrices produce sparse columns. ::
637
638
sage: A = matrix(QQ, 2, range(4), sparse=True)
639
sage: v = A.columns()[0]
640
sage: v.is_sparse()
641
True
642
643
TESTS::
644
645
sage: A = matrix(QQ, 4, range(16))
646
sage: A.columns('junk')
647
Traceback (most recent call last):
648
...
649
ValueError: 'copy' must be True or False, not junk
650
"""
651
if not copy in [True, False]:
652
msg = "'copy' must be True or False, not {0}"
653
raise ValueError(msg.format(copy))
654
x = self.fetch('columns')
655
if not x is None:
656
if copy: return list(x)
657
return x
658
if self.is_sparse():
659
columns = self.sparse_columns(copy=copy)
660
else:
661
columns = self.dense_columns(copy=copy)
662
self.cache('columns', columns)
663
if copy: return list(columns)
664
return columns
665
666
def rows(self, copy=True):
667
r"""
668
Return a list of the rows of self.
669
670
INPUT:
671
672
- ``copy`` - (default: True) if True, return a copy of the list
673
of rows which is safe to change.
674
675
If ``self`` is a sparse matrix, rows are returned as sparse vectors,
676
otherwise returned vectors are dense.
677
678
EXAMPLES::
679
680
sage: matrix(3, [1..9]).rows()
681
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
682
sage: matrix(RR, 2, [sqrt(2), pi, exp(1), 0]).rows()
683
[(1.41421356237310, 3.14159265358979), (2.71828182845905, 0.000000000000000)]
684
sage: matrix(RR, 0, 2, []).rows()
685
[]
686
sage: matrix(RR, 2, 0, []).rows()
687
[(), ()]
688
sage: m = matrix(RR, 3, 3, {(1,2): pi, (2, 2): -1, (0,1): sqrt(2)})
689
sage: parent(m.rows()[0])
690
Sparse vector space of dimension 3 over Real Field with 53 bits of precision
691
692
Sparse matrices produce sparse rows. ::
693
694
sage: A = matrix(QQ, 2, range(4), sparse=True)
695
sage: v = A.rows()[0]
696
sage: v.is_sparse()
697
True
698
699
TESTS::
700
701
sage: A = matrix(QQ, 4, range(16))
702
sage: A.rows('junk')
703
Traceback (most recent call last):
704
...
705
ValueError: 'copy' must be True or False, not junk
706
"""
707
if not copy in [True, False]:
708
msg = "'copy' must be True or False, not {0}"
709
raise ValueError(msg.format(copy))
710
x = self.fetch('rows')
711
if not x is None:
712
if copy: return list(x)
713
return x
714
if self.is_sparse():
715
rows = self.sparse_rows(copy=copy)
716
else:
717
rows = self.dense_rows(copy=copy)
718
self.cache('rows', rows)
719
if copy: return list(rows)
720
return rows
721
722
def dense_columns(self, copy=True):
723
"""
724
Return list of the dense columns of self.
725
726
INPUT:
727
728
- ``copy`` - (default: True) if True, return a copy so you can
729
modify it safely
730
731
EXAMPLES:
732
733
An example over the integers::
734
735
sage: a = matrix(3,3,range(9)); a
736
[0 1 2]
737
[3 4 5]
738
[6 7 8]
739
sage: a.dense_columns()
740
[(0, 3, 6), (1, 4, 7), (2, 5, 8)]
741
742
We do an example over a polynomial ring::
743
744
sage: R.<x> = QQ[ ]
745
sage: a = matrix(R, 2, [x,x^2, 2/3*x,1+x^5]); a
746
[ x x^2]
747
[ 2/3*x x^5 + 1]
748
sage: a.dense_columns()
749
[(x, 2/3*x), (x^2, x^5 + 1)]
750
sage: a = matrix(R, 2, [x,x^2, 2/3*x,1+x^5], sparse=True)
751
sage: c = a.dense_columns(); c
752
[(x, 2/3*x), (x^2, x^5 + 1)]
753
sage: parent(c[1])
754
Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
755
756
TESTS:
757
758
Check that the returned rows are immutable as per :trac:`14874`::
759
760
sage: m = Mat(ZZ,3,3)(range(9))
761
sage: v = m.dense_columns()
762
sage: map(lambda x: x.is_mutable(), v)
763
[False, False, False]
764
"""
765
x = self.fetch('dense_columns')
766
if not x is None:
767
if copy: return list(x)
768
return x
769
cdef Py_ssize_t i
770
A = self if self.is_dense() else self.dense_matrix()
771
C = [A.column(i) for i in range(self._ncols)]
772
773
# Make the vectors immutable since we are caching them
774
map(lambda x: x.set_immutable(), C)
775
776
# cache result
777
self.cache('dense_columns', C)
778
if copy:
779
return list(C)
780
else:
781
return C
782
783
def dense_rows(self, copy=True):
784
"""
785
Return list of the dense rows of self.
786
787
INPUT:
788
789
- ``copy`` - (default: True) if True, return a copy so you can
790
modify it safely (note that the individual vectors in the copy
791
should not be modified since they are mutable!)
792
793
EXAMPLES::
794
795
sage: m = matrix(3, range(9)); m
796
[0 1 2]
797
[3 4 5]
798
[6 7 8]
799
sage: v = m.dense_rows(); v
800
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
801
sage: v is m.dense_rows()
802
False
803
sage: m.dense_rows(copy=False) is m.dense_rows(copy=False)
804
True
805
sage: m[0,0] = 10
806
sage: m.dense_rows()
807
[(10, 1, 2), (3, 4, 5), (6, 7, 8)]
808
809
TESTS:
810
811
Check that the returned rows are immutable as per :trac:`14874`::
812
813
sage: m = Mat(ZZ,3,3)(range(9))
814
sage: v = m.dense_rows()
815
sage: map(lambda x: x.is_mutable(), v)
816
[False, False, False]
817
"""
818
x = self.fetch('dense_rows')
819
if not x is None:
820
if copy: return list(x)
821
return x
822
823
cdef Py_ssize_t i
824
A = self if self.is_dense() else self.dense_matrix()
825
R = [A.row(i) for i in range(self._nrows)]
826
827
# Make the vectors immutable since we are caching them
828
map(lambda x: x.set_immutable(), R)
829
830
# cache result
831
self.cache('dense_rows', R)
832
if copy:
833
return list(R)
834
else:
835
return R
836
837
838
def sparse_columns(self, copy=True):
839
r"""
840
Return a list of the columns of ``self`` as sparse vectors (or free module elements).
841
842
INPUT:
843
844
- ``copy`` - (default: True) if True, return a copy so you can
845
modify it safely
846
847
EXAMPLES::
848
849
sage: a = matrix(2,3,range(6)); a
850
[0 1 2]
851
[3 4 5]
852
sage: v = a.sparse_columns(); v
853
[(0, 3), (1, 4), (2, 5)]
854
sage: v[1].is_sparse()
855
True
856
857
TESTS:
858
859
Columns of sparse matrices having no columns were fixed on :trac:`10714`::
860
861
sage: m = matrix(10, 0, sparse=True)
862
sage: m.ncols()
863
0
864
sage: m.columns()
865
[]
866
867
Check that the returned columns are immutable as per :trac:`14874`::
868
869
sage: m = Mat(ZZ,3,3,sparse=True)(range(9))
870
sage: v = m.sparse_columns()
871
sage: map(lambda x: x.is_mutable(), v)
872
[False, False, False]
873
"""
874
x = self.fetch('sparse_columns')
875
if not x is None:
876
if copy: return list(x)
877
return x
878
879
cdef Py_ssize_t i, j
880
C = []
881
if self._ncols > 0:
882
F = sage.modules.free_module.FreeModule(self._base_ring, self._nrows, sparse=True)
883
884
k = 0
885
entries = {}
886
for i, j in self.nonzero_positions(copy=False, column_order=True):
887
if j > k:
888
# new column -- emit vector
889
while len(C) < k:
890
C.append(F(0))
891
C.append(F(entries, coerce=False, copy=False, check=False))
892
entries = {}
893
k = j
894
entries[i] = self.get_unsafe(i, j)
895
896
# finish up
897
while len(C) < k:
898
C.append(F(0))
899
C.append(F(entries, coerce=False, copy=False, check=False))
900
while len(C) < self._ncols:
901
C.append(F(0))
902
903
# Make the vectors immutable since we are caching them
904
map(lambda x: x.set_immutable(), C)
905
906
# cache and return result
907
self.cache('sparse_columns', C)
908
if copy:
909
return list(C)
910
else:
911
return C
912
913
def sparse_rows(self, copy=True):
914
r"""
915
Return a list of the rows of ``self`` as sparse vectors (or free module elements).
916
917
INPUT:
918
919
- ``copy`` - (default: True) if True, return a copy so you can
920
modify it safely
921
922
EXAMPLES::
923
924
sage: m = Mat(ZZ,3,3,sparse=True)(range(9)); m
925
[0 1 2]
926
[3 4 5]
927
[6 7 8]
928
sage: v = m.sparse_rows(); v
929
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
930
sage: m.sparse_rows(copy=False) is m.sparse_rows(copy=False)
931
True
932
sage: v[1].is_sparse()
933
True
934
sage: m[0,0] = 10
935
sage: m.sparse_rows()
936
[(10, 1, 2), (3, 4, 5), (6, 7, 8)]
937
938
TESTS:
939
940
Rows of sparse matrices having no rows were fixed on :trac:`10714`::
941
942
sage: m = matrix(0, 10, sparse=True)
943
sage: m.nrows()
944
0
945
sage: m.rows()
946
[]
947
948
Check that the returned rows are immutable as per :trac:`14874`::
949
950
sage: m = Mat(ZZ,3,3,sparse=True)(range(9))
951
sage: v = m.sparse_rows()
952
sage: map(lambda x: x.is_mutable(), v)
953
[False, False, False]
954
"""
955
x = self.fetch('sparse_rows')
956
if not x is None:
957
if copy: return list(x)
958
return x
959
960
cdef Py_ssize_t i, j
961
R = []
962
if self._nrows > 0:
963
F = sage.modules.free_module.FreeModule(self._base_ring, self._ncols, sparse=True)
964
965
k = 0
966
entries = {}
967
for i, j in self.nonzero_positions(copy=False):
968
if i > k:
969
# new row -- emit vector
970
while len(R) < k:
971
R.append(F(0))
972
R.append(F(entries, coerce=False, copy=False, check=False))
973
entries = {}
974
k = i
975
entries[j] = self.get_unsafe(i, j)
976
977
# finish up
978
while len(R) < k:
979
R.append(F(0))
980
R.append(F(entries, coerce=False, copy=False, check=False))
981
while len(R) < self._nrows:
982
R.append(F(0))
983
984
# Make the vectors immutable since we are caching them
985
map(lambda x: x.set_immutable(), R)
986
987
# cache and return result
988
self.cache('sparse_rows', R)
989
if copy:
990
return list(R)
991
else:
992
return R
993
994
def column(self, Py_ssize_t i, from_list=False):
995
"""
996
Return the ``i``'th column of this matrix as a vector.
997
998
This column is a dense vector if and only if the matrix is a dense
999
matrix.
1000
1001
INPUT:
1002
1003
- ``i`` - integer
1004
1005
- ``from_list`` - bool (default: False); if true, returns the
1006
``i``'th element of ``self.columns()`` (see :func:`columns()`),
1007
which may be faster, but requires building a list of all
1008
columns the first time it is called after an entry of the
1009
matrix is changed.
1010
1011
1012
EXAMPLES::
1013
1014
sage: a = matrix(2,3,range(6)); a
1015
[0 1 2]
1016
[3 4 5]
1017
sage: a.column(1)
1018
(1, 4)
1019
1020
If the column is negative, it wraps around, just like with list
1021
indexing, e.g., -1 gives the right-most column::
1022
1023
sage: a.column(-1)
1024
(2, 5)
1025
1026
TESTS::
1027
1028
sage: a = matrix(2,3,range(6)); a
1029
[0 1 2]
1030
[3 4 5]
1031
sage: a.column(3)
1032
Traceback (most recent call last):
1033
...
1034
IndexError: column index out of range
1035
sage: a.column(-4)
1036
Traceback (most recent call last):
1037
...
1038
IndexError: column index out of range
1039
"""
1040
if self._ncols == 0:
1041
raise IndexError, "matrix has no columns"
1042
if i >= self._ncols or i < -self._ncols:
1043
raise IndexError, "column index out of range"
1044
i = i % self._ncols
1045
if i < 0:
1046
i = i + self._ncols
1047
if from_list:
1048
return self.columns(copy=False)[i]
1049
cdef Py_ssize_t j
1050
V = sage.modules.free_module.FreeModule(self._base_ring,
1051
self._nrows, sparse=self.is_sparse())
1052
tmp = [self.get_unsafe(j,i) for j in range(self._nrows)]
1053
return V(tmp, coerce=False, copy=False, check=False)
1054
1055
def row(self, Py_ssize_t i, from_list=False):
1056
"""
1057
Return the ``i``'th row of this matrix as a vector.
1058
1059
This row is a dense vector if and only if the matrix is a dense
1060
matrix.
1061
1062
INPUT:
1063
1064
- ``i`` - integer
1065
1066
- ``from_list`` - bool (default: False); if true, returns the
1067
``i``'th element of ``self.rows()`` (see :func:`rows`), which
1068
may be faster, but requires building a list of all rows the
1069
first time it is called after an entry of the matrix is
1070
changed.
1071
1072
EXAMPLES::
1073
1074
sage: a = matrix(2,3,range(6)); a
1075
[0 1 2]
1076
[3 4 5]
1077
sage: a.row(0)
1078
(0, 1, 2)
1079
sage: a.row(1)
1080
(3, 4, 5)
1081
sage: a.row(-1) # last row
1082
(3, 4, 5)
1083
1084
TESTS::
1085
1086
sage: a = matrix(2,3,range(6)); a
1087
[0 1 2]
1088
[3 4 5]
1089
sage: a.row(2)
1090
Traceback (most recent call last):
1091
...
1092
IndexError: row index out of range
1093
sage: a.row(-3)
1094
Traceback (most recent call last):
1095
...
1096
IndexError: row index out of range
1097
"""
1098
if self._nrows == 0:
1099
raise IndexError, "matrix has no rows"
1100
if i >= self._nrows or i < -self._nrows:
1101
raise IndexError, "row index out of range"
1102
i = i % self._nrows
1103
if i < 0:
1104
i = i + self._nrows
1105
if from_list:
1106
return self.rows(copy=False)[i]
1107
cdef Py_ssize_t j
1108
V = sage.modules.free_module.FreeModule(self._base_ring,
1109
self._ncols, sparse=self.is_sparse())
1110
tmp = [self.get_unsafe(i,j) for j in range(self._ncols)]
1111
return V(tmp, coerce=False, copy=False, check=False)
1112
1113
1114
###########################################################################
1115
# Building matrices out of other matrices, rows, or columns
1116
###########################################################################
1117
def stack(self, bottom, subdivide=False):
1118
r"""
1119
Returns a new matrix formed by appending the matrix
1120
(or vector) ``bottom`` beneath ``self``.
1121
1122
INPUT:
1123
1124
- ``bottom`` - a matrix, vector or free module element, whose
1125
dimensions are compatible with ``self``.
1126
1127
- ``subdivide`` - default: ``False`` - request the resulting
1128
matrix to have a new subdivision, separating ``self`` from ``bottom``.
1129
1130
OUTPUT:
1131
1132
A new matrix formed by appending ``bottom`` beneath ``self``.
1133
If ``bottom`` is a vector (or free module element) then in this context
1134
it is appropriate to consider it as a row vector. (The code first
1135
converts a vector to a 1-row matrix.)
1136
1137
If ``subdivide`` is ``True`` then any row subdivisions for
1138
the two matrices are preserved, and a new subdivision is added
1139
between ``self`` and ``bottom``. If the column divisions are
1140
identical, then they are preserved, otherwise they are discarded.
1141
When ``subdivide`` is ``False`` there is no subdivision information
1142
in the result.
1143
1144
.. warning::
1145
If ``subdivide`` is ``True`` then unequal column subdivisions
1146
will be discarded, since it would be ambiguous how to interpret
1147
them. If the subdivision behavior is not what you need,
1148
you can manage subdivisions yourself with methods like
1149
:meth:`~sage.matrix.matrix2.Matrix.subdivisions`
1150
and
1151
:meth:`~sage.matrix.matrix2.Matrix.subdivide`.
1152
You might also find :func:`~sage.matrix.constructor.block_matrix`
1153
or
1154
:func:`~sage.matrix.constructor.block_diagonal_matrix`
1155
useful and simpler in some instances.
1156
1157
1158
EXAMPLES:
1159
1160
Stacking with a matrix. ::
1161
1162
sage: A = matrix(QQ, 4, 3, range(12))
1163
sage: B = matrix(QQ, 3, 3, range(9))
1164
sage: A.stack(B)
1165
[ 0 1 2]
1166
[ 3 4 5]
1167
[ 6 7 8]
1168
[ 9 10 11]
1169
[ 0 1 2]
1170
[ 3 4 5]
1171
[ 6 7 8]
1172
1173
Stacking with a vector. ::
1174
1175
sage: A = matrix(QQ, 3, 2, [0, 2, 4, 6, 8, 10])
1176
sage: v = vector(QQ, 2, [100, 200])
1177
sage: A.stack(v)
1178
[ 0 2]
1179
[ 4 6]
1180
[ 8 10]
1181
[100 200]
1182
1183
Errors are raised if the sizes are incompatible. ::
1184
1185
sage: A = matrix(RR, [[1, 2],[3, 4]])
1186
sage: B = matrix(RR, [[10, 20, 30], [40, 50, 60]])
1187
sage: A.stack(B)
1188
Traceback (most recent call last):
1189
...
1190
TypeError: number of columns must be the same, 2 != 3
1191
1192
sage: v = vector(RR, [100, 200, 300])
1193
sage: A.stack(v)
1194
Traceback (most recent call last):
1195
...
1196
TypeError: number of columns must be the same, 2 != 3
1197
1198
Setting ``subdivide`` to ``True`` will, in its simplest form,
1199
add a subdivision between ``self`` and ``bottom``. ::
1200
1201
sage: A = matrix(QQ, 2, 5, range(10))
1202
sage: B = matrix(QQ, 3, 5, range(15))
1203
sage: A.stack(B, subdivide=True)
1204
[ 0 1 2 3 4]
1205
[ 5 6 7 8 9]
1206
[--------------]
1207
[ 0 1 2 3 4]
1208
[ 5 6 7 8 9]
1209
[10 11 12 13 14]
1210
1211
Row subdivisions are preserved by stacking, and enriched,
1212
if subdivisions are requested. (So multiple stackings can
1213
be recorded.) ::
1214
1215
sage: A = matrix(QQ, 2, 4, range(8))
1216
sage: A.subdivide([1], None)
1217
sage: B = matrix(QQ, 3, 4, range(12))
1218
sage: B.subdivide([2], None)
1219
sage: A.stack(B, subdivide=True)
1220
[ 0 1 2 3]
1221
[-----------]
1222
[ 4 5 6 7]
1223
[-----------]
1224
[ 0 1 2 3]
1225
[ 4 5 6 7]
1226
[-----------]
1227
[ 8 9 10 11]
1228
1229
Column subdivisions can be preserved, but only if they are identical.
1230
Otherwise, this information is discarded and must be managed
1231
separately. ::
1232
1233
sage: A = matrix(QQ, 2, 5, range(10))
1234
sage: A.subdivide(None, [2,4])
1235
sage: B = matrix(QQ, 3, 5, range(15))
1236
sage: B.subdivide(None, [2,4])
1237
sage: A.stack(B, subdivide=True)
1238
[ 0 1| 2 3| 4]
1239
[ 5 6| 7 8| 9]
1240
[-----+-----+--]
1241
[ 0 1| 2 3| 4]
1242
[ 5 6| 7 8| 9]
1243
[10 11|12 13|14]
1244
1245
sage: A.subdivide(None, [1,2])
1246
sage: A.stack(B, subdivide=True)
1247
[ 0 1 2 3 4]
1248
[ 5 6 7 8 9]
1249
[--------------]
1250
[ 0 1 2 3 4]
1251
[ 5 6 7 8 9]
1252
[10 11 12 13 14]
1253
1254
The result retains the base ring of ``self`` by coercing
1255
the elements of ``bottom`` into the base ring of ``self``. ::
1256
1257
sage: A = matrix(QQ, 1, 2, [1,2])
1258
sage: B = matrix(RR, 1, 2, [sin(1.1), sin(2.2)])
1259
sage: C = A.stack(B); C
1260
[ 1 2]
1261
[183017397/205358938 106580492/131825561]
1262
sage: C.parent()
1263
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
1264
1265
sage: D = B.stack(A); D
1266
[0.891207360061435 0.808496403819590]
1267
[ 1.00000000000000 2.00000000000000]
1268
sage: D.parent()
1269
Full MatrixSpace of 2 by 2 dense matrices over Real Field with 53 bits of precision
1270
1271
Sometimes it is not possible to coerce into the base ring
1272
of ``self``. A solution is to change the base ring of ``self``
1273
to a more expansive ring. Here we mix the rationals with
1274
a ring of polynomials with rational coefficients. ::
1275
1276
sage: R = PolynomialRing(QQ, 'y')
1277
sage: A = matrix(QQ, 1, 2, [1,2])
1278
sage: B = matrix(R, 1, 2, ['y', 'y^2'])
1279
1280
sage: C = B.stack(A); C
1281
[ y y^2]
1282
[ 1 2]
1283
sage: C.parent()
1284
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field
1285
1286
sage: D = A.stack(B)
1287
Traceback (most recent call last):
1288
...
1289
TypeError: not a constant polynomial
1290
1291
sage: E = A.change_ring(R)
1292
sage: F = E.stack(B); F
1293
[ 1 2]
1294
[ y y^2]
1295
sage: F.parent()
1296
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field
1297
1298
TESTS:
1299
1300
A legacy test from the original implementation. ::
1301
1302
sage: M = Matrix(QQ, 2, 3, range(6))
1303
sage: N = Matrix(QQ, 1, 3, [10,11,12])
1304
sage: M.stack(N)
1305
[ 0 1 2]
1306
[ 3 4 5]
1307
[10 11 12]
1308
1309
AUTHOR:
1310
1311
- Rob Beezer (2011-03-19) - rewritten to mirror code for :meth:`augment`
1312
"""
1313
from sage.matrix.constructor import matrix
1314
1315
if hasattr(bottom, '_vector_'):
1316
bottom = bottom.row()
1317
if not isinstance(bottom, sage.matrix.matrix1.Matrix):
1318
raise TypeError('a matrix must be stacked with another matrix, or '
1319
'a vector')
1320
1321
cdef Matrix other
1322
other = bottom
1323
1324
if self._ncols != other._ncols:
1325
raise TypeError('number of columns must be the same, '
1326
'{0} != {1}'.format(self._ncols, other._ncols))
1327
if not (self._base_ring is other.base_ring()):
1328
other = other.change_ring(self._base_ring)
1329
1330
cdef Matrix Z
1331
Z = self.new_matrix(nrows = self._nrows + other._nrows)
1332
1333
cdef Py_ssize_t r, c
1334
for r from 0 <= r < self._nrows:
1335
for c from 0 <= c < self._ncols:
1336
Z.set_unsafe(r,c, self.get_unsafe(r,c))
1337
nr = self.nrows()
1338
1339
for r from 0 <= r < other._nrows:
1340
for c from 0 <= c < other._ncols:
1341
Z.set_unsafe(r+nr, c, other.get_unsafe(r,c))
1342
1343
if subdivide:
1344
Z._subdivide_on_stack(self, other)
1345
1346
return Z
1347
1348
def augment(self, right, subdivide=False):
1349
r"""
1350
Returns a new matrix formed by appending the matrix (or vector)
1351
``right`` on the right side of ``self``.
1352
1353
INPUT:
1354
1355
- ``right`` - a matrix, vector or free module element, whose
1356
dimensions are compatible with ``self``.
1357
1358
- ``subdivide`` - default: ``False`` - request the resulting
1359
matrix to have a new subdivision, separating ``self`` from
1360
``right``.
1361
1362
OUTPUT:
1363
1364
A new matrix formed by appending ``right`` onto the right side
1365
of ``self``. If ``right`` is a vector (or free module element)
1366
then in this context it is appropriate to consider it as a
1367
column vector. (The code first converts a vector to a 1-column
1368
matrix.)
1369
1370
If ``subdivide`` is ``True`` then any column subdivisions for
1371
the two matrices are preserved, and a new subdivision is added
1372
between ``self`` and ``right``. If the row divisions are
1373
identical, then they are preserved, otherwise they are
1374
discarded. When ``subdivide`` is ``False`` there is no
1375
subdivision information in the result.
1376
1377
.. warning::
1378
If ``subdivide`` is ``True`` then unequal row subdivisions
1379
will be discarded, since it would be ambiguous how to
1380
interpret them. If the subdivision behavior is not what you
1381
need, you can manage subdivisions yourself with methods like
1382
:meth:`~sage.matrix.matrix2.Matrix.get_subdivisions` and
1383
:meth:`~sage.matrix.matrix2.Matrix.subdivide`. You might
1384
also find :func:`~sage.matrix.constructor.block_matrix` or
1385
:func:`~sage.matrix.constructor.block_diagonal_matrix`
1386
useful and simpler in some instances.
1387
1388
1389
EXAMPLES:
1390
1391
Augmenting with a matrix. ::
1392
1393
sage: A = matrix(QQ, 3, range(12))
1394
sage: B = matrix(QQ, 3, range(9))
1395
sage: A.augment(B)
1396
[ 0 1 2 3 0 1 2]
1397
[ 4 5 6 7 3 4 5]
1398
[ 8 9 10 11 6 7 8]
1399
1400
Augmenting with a vector. ::
1401
1402
sage: A = matrix(QQ, 2, [0, 2, 4, 6, 8, 10])
1403
sage: v = vector(QQ, 2, [100, 200])
1404
sage: A.augment(v)
1405
[ 0 2 4 100]
1406
[ 6 8 10 200]
1407
1408
Errors are raised if the sizes are incompatible. ::
1409
1410
sage: A = matrix(RR, [[1, 2],[3, 4]])
1411
sage: B = matrix(RR, [[10, 20], [30, 40], [50, 60]])
1412
sage: A.augment(B)
1413
Traceback (most recent call last):
1414
...
1415
TypeError: number of rows must be the same, 2 != 3
1416
1417
sage: v = vector(RR, [100, 200, 300])
1418
sage: A.augment(v)
1419
Traceback (most recent call last):
1420
...
1421
TypeError: number of rows must be the same, 2 != 3
1422
1423
Setting ``subdivide`` to ``True`` will, in its simplest form,
1424
add a subdivision between ``self`` and ``right``. ::
1425
1426
sage: A = matrix(QQ, 3, range(12))
1427
sage: B = matrix(QQ, 3, range(15))
1428
sage: A.augment(B, subdivide=True)
1429
[ 0 1 2 3| 0 1 2 3 4]
1430
[ 4 5 6 7| 5 6 7 8 9]
1431
[ 8 9 10 11|10 11 12 13 14]
1432
1433
Column subdivisions are preserved by augmentation, and enriched,
1434
if subdivisions are requested. (So multiple augmentations can
1435
be recorded.) ::
1436
1437
sage: A = matrix(QQ, 3, range(6))
1438
sage: A.subdivide(None, [1])
1439
sage: B = matrix(QQ, 3, range(9))
1440
sage: B.subdivide(None, [2])
1441
sage: A.augment(B, subdivide=True)
1442
[0|1|0 1|2]
1443
[2|3|3 4|5]
1444
[4|5|6 7|8]
1445
1446
Row subdivisions can be preserved, but only if they are
1447
identical. Otherwise, this information is discarded and must be
1448
managed separately. ::
1449
1450
sage: A = matrix(QQ, 3, range(6))
1451
sage: A.subdivide([1,3], None)
1452
sage: B = matrix(QQ, 3, range(9))
1453
sage: B.subdivide([1,3], None)
1454
sage: A.augment(B, subdivide=True)
1455
[0 1|0 1 2]
1456
[---+-----]
1457
[2 3|3 4 5]
1458
[4 5|6 7 8]
1459
[---+-----]
1460
1461
sage: A.subdivide([1,2], None)
1462
sage: A.augment(B, subdivide=True)
1463
[0 1|0 1 2]
1464
[2 3|3 4 5]
1465
[4 5|6 7 8]
1466
1467
The result retains the base ring of ``self`` by coercing the
1468
elements of ``right`` into the base ring of ``self``. ::
1469
1470
sage: A = matrix(QQ, 2, [1,2])
1471
sage: B = matrix(RR, 2, [sin(1.1), sin(2.2)])
1472
sage: C = A.augment(B); C
1473
[ 1 183017397/205358938]
1474
[ 2 106580492/131825561]
1475
sage: C.parent()
1476
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
1477
1478
sage: D = B.augment(A); D
1479
[0.89120736006... 1.00000000000000]
1480
[0.80849640381... 2.00000000000000]
1481
sage: D.parent()
1482
Full MatrixSpace of 2 by 2 dense matrices over Real Field with 53 bits of precision
1483
1484
Sometimes it is not possible to coerce into the base ring of
1485
``self``. A solution is to change the base ring of ``self`` to
1486
a more expansive ring. Here we mix the rationals with a ring of
1487
polynomials with rational coefficients. ::
1488
1489
sage: R = PolynomialRing(QQ, 'y')
1490
sage: A = matrix(QQ, 1, [1,2])
1491
sage: B = matrix(R, 1, ['y', 'y^2'])
1492
1493
sage: C = B.augment(A); C
1494
[ y y^2 1 2]
1495
sage: C.parent()
1496
Full MatrixSpace of 1 by 4 dense matrices over Univariate Polynomial Ring in y over Rational Field
1497
1498
sage: D = A.augment(B)
1499
Traceback (most recent call last):
1500
...
1501
TypeError: not a constant polynomial
1502
1503
sage: E = A.change_ring(R)
1504
sage: F = E.augment(B); F
1505
[ 1 2 y y^2]
1506
sage: F.parent()
1507
Full MatrixSpace of 1 by 4 dense matrices over Univariate Polynomial Ring in y over Rational Field
1508
1509
AUTHORS:
1510
1511
- Naqi Jaffery (2006-01-24): examples
1512
- Rob Beezer (2010-12-07): vector argument, docstring, subdivisions
1513
"""
1514
from sage.matrix.constructor import matrix
1515
1516
if hasattr(right, '_vector_'):
1517
right = right.column()
1518
if not isinstance(right, sage.matrix.matrix1.Matrix):
1519
raise TypeError("a matrix must be augmented with another matrix, "
1520
"or a vector")
1521
1522
cdef Matrix other
1523
other = right
1524
1525
if self._nrows != other._nrows:
1526
raise TypeError('number of rows must be the same, '
1527
'{0} != {1}'.format(self._nrows, other._nrows))
1528
if not (self._base_ring is other.base_ring()):
1529
other = other.change_ring(self._base_ring)
1530
1531
cdef Matrix Z
1532
Z = self.new_matrix(ncols = self._ncols + other._ncols)
1533
1534
cdef Py_ssize_t r, c
1535
for r from 0 <= r < self._nrows:
1536
for c from 0 <= c < self._ncols:
1537
Z.set_unsafe(r,c, self.get_unsafe(r,c))
1538
nc = self.ncols()
1539
1540
for r from 0 <= r < other._nrows:
1541
for c from 0 <= c < other._ncols:
1542
Z.set_unsafe(r, c+nc, other.get_unsafe(r,c))
1543
1544
if subdivide:
1545
Z._subdivide_on_augment(self, other)
1546
1547
return Z
1548
1549
def matrix_from_columns(self, columns):
1550
"""
1551
Return the matrix constructed from self using columns with indices
1552
in the columns list.
1553
1554
EXAMPLES::
1555
1556
sage: M = MatrixSpace(Integers(8),3,3)
1557
sage: A = M(range(9)); A
1558
[0 1 2]
1559
[3 4 5]
1560
[6 7 0]
1561
sage: A.matrix_from_columns([2,1])
1562
[2 1]
1563
[5 4]
1564
[0 7]
1565
"""
1566
if not (PY_TYPE_CHECK(columns, list) or PY_TYPE_CHECK(columns, tuple)):
1567
raise TypeError, "columns (=%s) must be a list of integers"%columns
1568
cdef Matrix A
1569
cdef Py_ssize_t ncols,k,r
1570
1571
ncols = PyList_GET_SIZE(columns)
1572
A = self.new_matrix(ncols = ncols)
1573
k = 0
1574
for i from 0 <= i < ncols:
1575
if columns[i] < 0 or columns[i] >= self._ncols:
1576
raise IndexError, "column %s out of range"%columns[i]
1577
for r from 0 <= r < self._nrows:
1578
A.set_unsafe(r,k, self.get_unsafe(r,columns[i]))
1579
k = k + 1
1580
return A
1581
1582
def delete_columns(self, dcols, check=True):
1583
"""
1584
Return the matrix constructed from deleting the columns with indices in the ``dcols`` list.
1585
1586
INPUT:
1587
1588
* ``dcols`` - list of indices of columns to be deleted from self.
1589
* ``check`` - checks whether any index in ``dcols`` is out of range. Defaults to ``True``.
1590
1591
SEE ALSO:
1592
The methods :meth:`delete_rows` and :meth:`matrix_from_columns` are related.
1593
1594
EXAMPLES::
1595
1596
sage: A = Matrix(3,4,range(12)); A
1597
[ 0 1 2 3]
1598
[ 4 5 6 7]
1599
[ 8 9 10 11]
1600
sage: A.delete_columns([0,2])
1601
[ 1 3]
1602
[ 5 7]
1603
[ 9 11]
1604
1605
``dcols`` can be a tuple. But only the underlying set of indices matters. ::
1606
1607
sage: A.delete_columns((2,0,2))
1608
[ 1 3]
1609
[ 5 7]
1610
[ 9 11]
1611
1612
The default is to check whether any index in ``dcols`` is out of range. ::
1613
1614
sage: A.delete_columns([-1,2,4])
1615
Traceback (most recent call last):
1616
...
1617
IndexError: [4, -1] contains invalid indices.
1618
sage: A.delete_columns([-1,2,4], check=False)
1619
[ 0 1 3]
1620
[ 4 5 7]
1621
[ 8 9 11]
1622
1623
TESTS:
1624
1625
The list of indices is checked. ::
1626
1627
sage: A.delete_columns('junk')
1628
Traceback (most recent call last):
1629
...
1630
TypeError: The argument must be a list or a tuple, not junk
1631
1632
AUTHORS:
1633
- Wai Yan Pong (2012-03-05)
1634
"""
1635
if not (PY_TYPE_CHECK(dcols, list) or PY_TYPE_CHECK(dcols, tuple)):
1636
raise TypeError("The argument must be a list or a tuple, not {l}".format(l=dcols))
1637
cdef list cols, diff_cols
1638
1639
if check:
1640
diff_cols = list(set(dcols).difference(set(range(self._ncols))))
1641
if not (diff_cols == []):
1642
raise IndexError("{d} contains invalid indices.".format(d=diff_cols))
1643
cols = [k for k in range(self._ncols) if not k in dcols]
1644
return self.matrix_from_columns(cols)
1645
1646
def matrix_from_rows(self, rows):
1647
"""
1648
Return the matrix constructed from self using rows with indices in
1649
the rows list.
1650
1651
EXAMPLES::
1652
1653
sage: M = MatrixSpace(Integers(8),3,3)
1654
sage: A = M(range(9)); A
1655
[0 1 2]
1656
[3 4 5]
1657
[6 7 0]
1658
sage: A.matrix_from_rows([2,1])
1659
[6 7 0]
1660
[3 4 5]
1661
"""
1662
if not (PY_TYPE_CHECK(rows, list) or PY_TYPE_CHECK(rows, tuple)):
1663
raise TypeError, "rows must be a list of integers"
1664
cdef Matrix A
1665
cdef Py_ssize_t nrows,k,c
1666
1667
nrows = PyList_GET_SIZE(rows)
1668
A = self.new_matrix(nrows = nrows)
1669
k = 0
1670
for i from 0 <= i < nrows:
1671
if rows[i] < 0 or rows[i] >= self._nrows:
1672
raise IndexError, "row %s out of range"%rows[i]
1673
for c from 0 <= c < self._ncols:
1674
A.set_unsafe(k,c, self.get_unsafe(rows[i],c))
1675
k += 1
1676
return A
1677
1678
1679
def delete_rows(self, drows, check=True):
1680
"""
1681
Return the matrix constructed from deleting the rows with indices in the ``drows`` list.
1682
1683
INPUT:
1684
1685
* ``drows`` - list of indices of rows to be deleted from self.
1686
* ``check`` - checks whether any index in ``drows`` is out of range. Defaults to ``True``.
1687
1688
SEE ALSO:
1689
The methods :meth:`delete_columns` and :meth:`matrix_from_rows` are related.
1690
1691
EXAMPLES::
1692
1693
sage: A = Matrix(4,3,range(12)); A
1694
[ 0 1 2]
1695
[ 3 4 5]
1696
[ 6 7 8]
1697
[ 9 10 11]
1698
sage: A.delete_rows([0,2])
1699
[ 3 4 5]
1700
[ 9 10 11]
1701
1702
``drows`` can be a tuple. But only the underlying set of indices matters. ::
1703
1704
sage: A.delete_rows((2,0,2))
1705
[ 3 4 5]
1706
[ 9 10 11]
1707
1708
The default is to check whether the any index in ``drows`` is out of range. ::
1709
1710
sage: A.delete_rows([-1,2,4])
1711
Traceback (most recent call last):
1712
...
1713
IndexError: [4, -1] contains invalid indices.
1714
sage: A.delete_rows([-1,2,4], check=False)
1715
[ 0 1 2]
1716
[ 3 4 5]
1717
[ 9 10 11]
1718
1719
TESTS:
1720
1721
The list of indices is checked. ::
1722
1723
sage: A.delete_rows('junk')
1724
Traceback (most recent call last):
1725
...
1726
TypeError: The argument must be a list or a tuple, not junk
1727
1728
AUTHORS:
1729
- Wai Yan Pong (2012-03-05)
1730
"""
1731
if not (PY_TYPE_CHECK(drows, list) or PY_TYPE_CHECK(drows, tuple)):
1732
raise TypeError("The argument must be a list or a tuple, not {l}".format(l=drows))
1733
cdef list rows, diff_rows
1734
1735
if check:
1736
diff_rows = list(set(drows).difference(set(range(self._nrows))))
1737
if not (diff_rows == []):
1738
raise IndexError("{d} contains invalid indices.".format(d=diff_rows))
1739
rows = [k for k in range(self._nrows) if not k in drows]
1740
return self.matrix_from_rows(rows)
1741
1742
def matrix_from_rows_and_columns(self, rows, columns):
1743
"""
1744
Return the matrix constructed from self from the given rows and
1745
columns.
1746
1747
EXAMPLES::
1748
1749
sage: M = MatrixSpace(Integers(8),3,3)
1750
sage: A = M(range(9)); A
1751
[0 1 2]
1752
[3 4 5]
1753
[6 7 0]
1754
sage: A.matrix_from_rows_and_columns([1], [0,2])
1755
[3 5]
1756
sage: A.matrix_from_rows_and_columns([1,2], [1,2])
1757
[4 5]
1758
[7 0]
1759
1760
Note that row and column indices can be reordered or repeated::
1761
1762
sage: A.matrix_from_rows_and_columns([2,1], [2,1])
1763
[0 7]
1764
[5 4]
1765
1766
For example here we take from row 1 columns 2 then 0 twice, and do
1767
this 3 times.
1768
1769
::
1770
1771
sage: A.matrix_from_rows_and_columns([1,1,1],[2,0,0])
1772
[5 3 3]
1773
[5 3 3]
1774
[5 3 3]
1775
1776
AUTHORS:
1777
1778
- Jaap Spies (2006-02-18)
1779
1780
- Didier Deshommes: some Pyrex speedups implemented
1781
"""
1782
if not PY_TYPE_CHECK(rows, list):
1783
raise TypeError, "rows must be a list of integers"
1784
if not PY_TYPE_CHECK(columns, list):
1785
raise TypeError, "columns must be a list of integers"
1786
1787
cdef Matrix A
1788
cdef Py_ssize_t nrows, ncols,k,r,i,j
1789
1790
r = 0
1791
ncols = PyList_GET_SIZE(columns)
1792
nrows = PyList_GET_SIZE(rows)
1793
A = self.new_matrix(nrows = nrows, ncols = ncols)
1794
1795
tmp = [el for el in columns if el >= 0 and el < self._ncols]
1796
columns = tmp
1797
if ncols != PyList_GET_SIZE(columns):
1798
raise IndexError, "column index out of range"
1799
1800
for i from 0 <= i < nrows:
1801
if rows[i] < 0 or rows[i] >= self._nrows:
1802
raise IndexError, "row %s out of range"%i
1803
k = 0
1804
for j from 0 <= j < ncols:
1805
A.set_unsafe(r,k, self.get_unsafe(rows[i],columns[j]))
1806
k += 1
1807
r += 1
1808
return A
1809
1810
def submatrix(self, Py_ssize_t row=0, Py_ssize_t col=0,
1811
Py_ssize_t nrows=-1, Py_ssize_t ncols=-1):
1812
"""
1813
Return the matrix constructed from self using the specified
1814
range of rows and columns.
1815
1816
INPUT:
1817
1818
- ``row``, ``col`` - index of the starting row and column.
1819
Indices start at zero.
1820
1821
- ``nrows``, ``ncols`` - (optional) number of rows and columns to
1822
take. If not provided, take all rows below and all columns to
1823
the right of the starting entry.
1824
1825
SEE ALSO:
1826
1827
The functions :func:`matrix_from_rows`,
1828
:func:`matrix_from_columns`, and
1829
:func:`matrix_from_rows_and_columns` allow one to select
1830
arbitrary subsets of rows and/or columns.
1831
1832
EXAMPLES:
1833
1834
Take the `3 \\times 3` submatrix starting from entry (1,1) in a
1835
`4 \\times 4` matrix::
1836
1837
sage: m = matrix(4, [1..16])
1838
sage: m.submatrix(1, 1)
1839
[ 6 7 8]
1840
[10 11 12]
1841
[14 15 16]
1842
1843
Same thing, except take only two rows::
1844
1845
sage: m.submatrix(1, 1, 2)
1846
[ 6 7 8]
1847
[10 11 12]
1848
1849
And now take only one column::
1850
1851
sage: m.submatrix(1, 1, 2, 1)
1852
[ 6]
1853
[10]
1854
1855
You can take zero rows or columns if you want::
1856
1857
sage: m.submatrix(1, 1, 0)
1858
[]
1859
sage: parent(m.submatrix(1, 1, 0))
1860
Full MatrixSpace of 0 by 3 dense matrices over Integer Ring
1861
"""
1862
if nrows == -1:
1863
nrows = self._nrows - row
1864
if ncols == -1:
1865
ncols = self._ncols - col
1866
return self.matrix_from_rows_and_columns(range(row, row+nrows), range(col, col+ncols))
1867
1868
1869
1870
def set_row(self, row, v):
1871
r"""
1872
Sets the entries of row ``row`` to the entries of ``v``.
1873
1874
INPUT:
1875
1876
- ``row`` - index of row to be set.
1877
1878
- ``v`` - a list or vector of the new entries.
1879
1880
OUTPUT:
1881
1882
Changes the matrix in-place, so there is no output.
1883
1884
EXAMPLES:
1885
1886
New entries may be contained in a vector.::
1887
1888
sage: A = matrix(QQ, 5, range(25))
1889
sage: u = vector(QQ, [0, -1, -2, -3, -4])
1890
sage: A.set_row(2, u)
1891
sage: A
1892
[ 0 1 2 3 4]
1893
[ 5 6 7 8 9]
1894
[ 0 -1 -2 -3 -4]
1895
[15 16 17 18 19]
1896
[20 21 22 23 24]
1897
1898
New entries may be in any sort of list.::
1899
1900
sage: A = matrix([[1, 2], [3, 4]]); A
1901
[1 2]
1902
[3 4]
1903
sage: A.set_row(0, [0, 0]); A
1904
[0 0]
1905
[3 4]
1906
sage: A.set_row(1, (0, 0)); A
1907
[0 0]
1908
[0 0]
1909
1910
TESTS::
1911
1912
sage: A = matrix([[1, 2], [3, 4]])
1913
sage: A.set_row(2, [0, 0]); A
1914
Traceback (most recent call last):
1915
...
1916
ValueError: row number must be between 0 and 1 (inclusive), not 2
1917
1918
sage: A.set_row(0, [0, 0, 0])
1919
Traceback (most recent call last):
1920
...
1921
ValueError: list of new entries must be of length 2 (not 3)
1922
1923
sage: A = matrix(2, [1, 2, 3, 4])
1924
sage: A.set_row(0, [1/3, 1]); A
1925
Traceback (most recent call last):
1926
...
1927
TypeError: Cannot set row with Rational Field elements over Integer Ring, use change_ring first.
1928
"""
1929
if len(v) != self._ncols:
1930
msg = "list of new entries must be of length {0} (not {1})"
1931
raise ValueError(msg.format(self._ncols, len(v)))
1932
if (row < 0) or (row >= self._nrows):
1933
msg = "row number must be between 0 and {0} (inclusive), not {1}"
1934
raise ValueError(msg.format(self._nrows-1, row))
1935
1936
try:
1937
for j in range(self._ncols):
1938
self[row, j] = v[j]
1939
except TypeError:
1940
msg = "Cannot set row with {0} elements over {1}, use change_ring first."
1941
raise TypeError(msg.format(v[j].parent(), self.base_ring()))
1942
1943
def set_column(self, col, v):
1944
r"""
1945
Sets the entries of column ``col`` to the entries of ``v``.
1946
1947
INPUT:
1948
1949
- ``col`` - index of column to be set.
1950
1951
- ``v`` - a list or vector of the new entries.
1952
1953
OUTPUT:
1954
1955
Changes the matrix in-place, so there is no output.
1956
1957
EXAMPLES:
1958
1959
New entries may be contained in a vector.::
1960
1961
sage: A = matrix(QQ, 5, range(25))
1962
sage: u = vector(QQ, [0, -1, -2, -3, -4])
1963
sage: A.set_column(2, u)
1964
sage: A
1965
[ 0 1 0 3 4]
1966
[ 5 6 -1 8 9]
1967
[10 11 -2 13 14]
1968
[15 16 -3 18 19]
1969
[20 21 -4 23 24]
1970
1971
New entries may be in any sort of list.::
1972
1973
sage: A = matrix([[1, 2], [3, 4]]); A
1974
[1 2]
1975
[3 4]
1976
sage: A.set_column(0, [0, 0]); A
1977
[0 2]
1978
[0 4]
1979
sage: A.set_column(1, (0, 0)); A
1980
[0 0]
1981
[0 0]
1982
1983
TESTS::
1984
1985
sage: A = matrix([[1, 2], [3, 4]])
1986
sage: A.set_column(2, [0, 0]); A
1987
Traceback (most recent call last):
1988
...
1989
ValueError: column number must be between 0 and 1 (inclusive), not 2
1990
1991
sage: A.set_column(0, [0, 0, 0])
1992
Traceback (most recent call last):
1993
...
1994
ValueError: list of new entries must be of length 2 (not 3)
1995
1996
sage: A = matrix(2, [1, 2, 3, 4])
1997
sage: A.set_column(0, [1/4, 1]); A
1998
Traceback (most recent call last):
1999
...
2000
TypeError: Cannot set column with Rational Field elements over Integer Ring, use change_ring first.
2001
"""
2002
if len(v) != self._nrows:
2003
msg = "list of new entries must be of length {0} (not {1})"
2004
raise ValueError(msg.format(self._nrows, len(v)))
2005
if (col < 0) or (col >= self._ncols):
2006
msg = "column number must be between 0 and {0} (inclusive), not {1}"
2007
raise ValueError(msg.format(self._ncols-1, col))
2008
2009
try:
2010
for i in range(self._nrows):
2011
self[i, col] = v[i]
2012
except TypeError:
2013
msg = "Cannot set column with {0} elements over {1}, use change_ring first."
2014
raise TypeError(msg.format(v[i].parent(), self.base_ring()))
2015
2016
2017
####################################################################################
2018
# Change of representation between dense and sparse.
2019
####################################################################################
2020
2021
def dense_matrix(self):
2022
"""
2023
If this matrix is sparse, return a dense matrix with the same
2024
entries. If this matrix is dense, return this matrix (not a copy).
2025
2026
.. note::
2027
2028
The definition of "dense" and "sparse" in Sage have nothing to
2029
do with the number of nonzero entries. Sparse and dense are
2030
properties of the underlying representation of the matrix.
2031
2032
EXAMPLES::
2033
2034
sage: A = MatrixSpace(QQ,2, sparse=True)([1,2,0,1])
2035
sage: A.is_sparse()
2036
True
2037
sage: B = A.dense_matrix()
2038
sage: B.is_sparse()
2039
False
2040
sage: A*B
2041
[1 4]
2042
[0 1]
2043
sage: A.parent()
2044
Full MatrixSpace of 2 by 2 sparse matrices over Rational Field
2045
sage: B.parent()
2046
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
2047
2048
In Sage, the product of a sparse and a dense matrix is always
2049
dense::
2050
2051
sage: (A*B).parent()
2052
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
2053
sage: (B*A).parent()
2054
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
2055
2056
TESTS:
2057
2058
Make sure that subdivisions are preserved when switching
2059
between dense and sparse matrices::
2060
2061
sage: a = matrix(ZZ, 3, range(9))
2062
sage: a.subdivide([1,2],2)
2063
sage: a.subdivisions()
2064
([1, 2], [2])
2065
sage: b = a.sparse_matrix().dense_matrix()
2066
sage: b.subdivisions()
2067
([1, 2], [2])
2068
"""
2069
if self.is_dense():
2070
return self
2071
cdef Matrix A
2072
A = self.new_matrix(self._nrows, self._ncols, 0, coerce=False,
2073
copy = False, sparse=False)
2074
for i,j in self.nonzero_positions():
2075
A.set_unsafe(i,j,self.get_unsafe(i,j))
2076
A.subdivide(self.subdivisions())
2077
return A
2078
2079
def sparse_matrix(self):
2080
"""
2081
If this matrix is dense, return a sparse matrix with the same
2082
entries. If this matrix is sparse, return this matrix (not a
2083
copy).
2084
2085
.. note::
2086
2087
The definition of "dense" and "sparse" in Sage have nothing
2088
to do with the number of nonzero entries. Sparse and dense are
2089
properties of the underlying representation of the matrix.
2090
2091
EXAMPLES::
2092
2093
sage: A = MatrixSpace(QQ,2, sparse=False)([1,2,0,1])
2094
sage: A.is_sparse()
2095
False
2096
sage: B = A.sparse_matrix()
2097
sage: B.is_sparse()
2098
True
2099
sage: A
2100
[1 2]
2101
[0 1]
2102
sage: B
2103
[1 2]
2104
[0 1]
2105
sage: A*B
2106
[1 4]
2107
[0 1]
2108
sage: A.parent()
2109
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
2110
sage: B.parent()
2111
Full MatrixSpace of 2 by 2 sparse matrices over Rational Field
2112
sage: (A*B).parent()
2113
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
2114
sage: (B*A).parent()
2115
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
2116
"""
2117
if self.is_sparse():
2118
return self
2119
A = self.new_matrix(self._nrows, self._ncols, entries = self.dict(), coerce=False,
2120
copy = False, sparse=True)
2121
A.subdivide(self.subdivisions())
2122
return A
2123
2124
def matrix_space(self, nrows=None, ncols=None, sparse=None):
2125
"""
2126
Return the ambient matrix space of self.
2127
2128
INPUT:
2129
2130
- ``nrows``, ``ncols`` - (optional) number of rows and columns in
2131
returned matrix space.
2132
- ``sparse`` - whether the returned matrix space uses sparse or
2133
dense matrices.
2134
2135
EXAMPLES::
2136
2137
sage: m = matrix(3, [1..9])
2138
sage: m.matrix_space()
2139
Full MatrixSpace of 3 by 3 dense matrices over Integer Ring
2140
sage: m.matrix_space(ncols=2)
2141
Full MatrixSpace of 3 by 2 dense matrices over Integer Ring
2142
sage: m.matrix_space(1)
2143
Full MatrixSpace of 1 by 3 dense matrices over Integer Ring
2144
sage: m.matrix_space(1, 2, True)
2145
Full MatrixSpace of 1 by 2 sparse matrices over Integer Ring
2146
"""
2147
from sage.matrix.matrix_space import MatrixSpace
2148
if nrows is None:
2149
nrows = self._nrows
2150
if ncols is None:
2151
ncols = self._ncols
2152
if sparse is None:
2153
sparse = self.is_sparse()
2154
base_ring = self._base_ring
2155
return MatrixSpace(base_ring, nrows, ncols, sparse)
2156
2157
def new_matrix(self, nrows=None, ncols=None, entries=None,
2158
coerce=True, copy=True, sparse=None):
2159
"""
2160
Create a matrix in the parent of this matrix with the given number
2161
of rows, columns, etc. The default parameters are the same as for
2162
self.
2163
2164
INPUT:
2165
2166
These three variables get sent to :func:`matrix_space`:
2167
2168
- ``nrows``, ``ncols`` - number of rows and columns in returned
2169
matrix. If not specified, defaults to ``None`` and will give a
2170
matrix of the same size as self.
2171
- ``sparse`` - whether returned matrix is sparse or not. Defaults
2172
to same value as self.
2173
2174
The remaining three variables (``coerce``, ``entries``, and
2175
``copy``) are used by
2176
:func:`sage.matrix.matrix_space.MatrixSpace` to construct the
2177
new matrix.
2178
2179
.. warning::
2180
2181
This function called with no arguments returns the zero
2182
matrix of the same dimension and sparseness of self.
2183
2184
EXAMPLES::
2185
2186
sage: A = matrix(ZZ,2,2,[1,2,3,4]); A
2187
[1 2]
2188
[3 4]
2189
sage: A.new_matrix()
2190
[0 0]
2191
[0 0]
2192
sage: A.new_matrix(1,1)
2193
[0]
2194
sage: A.new_matrix(3,3).parent()
2195
Full MatrixSpace of 3 by 3 dense matrices over Integer Ring
2196
2197
::
2198
2199
sage: A = matrix(RR,2,3,[1.1,2.2,3.3,4.4,5.5,6.6]); A
2200
[1.10000000000000 2.20000000000000 3.30000000000000]
2201
[4.40000000000000 5.50000000000000 6.60000000000000]
2202
sage: A.new_matrix()
2203
[0.000000000000000 0.000000000000000 0.000000000000000]
2204
[0.000000000000000 0.000000000000000 0.000000000000000]
2205
sage: A.new_matrix().parent()
2206
Full MatrixSpace of 2 by 3 dense matrices over Real Field with 53 bits of precision
2207
2208
"""
2209
if self._nrows == nrows and self._ncols == ncols and (sparse is None or self.is_sparse() == sparse):
2210
return self._parent(entries=entries, coerce=coerce, copy=copy)
2211
return self.matrix_space(nrows, ncols, sparse=sparse)(entries=entries,
2212
coerce=coerce, copy=copy)
2213
def block_sum(self, Matrix other):
2214
"""
2215
Return the block matrix that has self and other on the diagonal::
2216
2217
[ self 0 ]
2218
[ 0 other ]
2219
2220
EXAMPLES::
2221
2222
sage: A = matrix(QQ[['t']], 2, range(1, 5))
2223
sage: A.block_sum(100*A)
2224
[ 1 2 0 0]
2225
[ 3 4 0 0]
2226
[ 0 0 100 200]
2227
[ 0 0 300 400]
2228
"""
2229
if not isinstance(other, Matrix):
2230
raise TypeError, "other must be a Matrix"
2231
top = self.augment(self.new_matrix(ncols=other._ncols))
2232
bottom = other.new_matrix(ncols=self._ncols).augment(other)
2233
return top.stack(bottom)
2234
2235
2236