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