Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/matrix/docs.py
4036 views
1
r"""
2
Matrices over an arbitrary ring
3
4
AUTHORS:
5
6
- William Stein
7
8
- Martin Albrecht: conversion to Pyrex
9
10
- Jaap Spies: various functions
11
12
- Gary Zablackis: fixed a sign bug in generic determinant.
13
14
- William Stein and Robert Bradshaw - complete restructuring.
15
16
- Rob Beezer - refactor kernel functions.
17
18
Elements of matrix spaces are of class ``Matrix`` (or a
19
class derived from Matrix). They can be either sparse or dense, and
20
can be defined over any base ring.
21
22
EXAMPLES:
23
24
We create the `2\times 3` matrix
25
26
.. math::
27
28
\left(\begin{matrix} 1&2&3\\4&5&6 \end{matrix}\right)
29
30
31
as an element of a matrix space over `\QQ`::
32
33
sage: M = MatrixSpace(QQ,2,3)
34
sage: A = M([1,2,3, 4,5,6]); A
35
[1 2 3]
36
[4 5 6]
37
sage: A.parent()
38
Full MatrixSpace of 2 by 3 dense matrices over Rational Field
39
40
Alternatively, we could create A more directly as follows (which
41
would completely avoid having to create the matrix space)::
42
43
sage: A = matrix(QQ, 2, [1,2,3, 4,5,6]); A
44
[1 2 3]
45
[4 5 6]
46
47
We next change the top-right entry of `A`. Note that matrix
48
indexing is `0`-based in Sage, so the top right entry is
49
`(0,2)`, which should be thought of as "row number
50
`0`, column number 2".
51
52
::
53
54
sage: A[0,2] = 389
55
sage: A
56
[ 1 2 389]
57
[ 4 5 6]
58
59
Also notice how matrices print. All columns have the same width and
60
entries in a given column are right justified. Next we compute the
61
reduced row echelon form of `A`.
62
63
::
64
65
sage: A.rref()
66
[ 1 0 -1933/3]
67
[ 0 1 1550/3]
68
69
70
Indexing
71
========
72
73
Sage has quite flexible ways of extracting elements or submatrices
74
from a matrix::
75
76
77
sage: m=[(1, -2, -1, -1,9), (1, 8, 6, 2,2), (1, 1, -1, 1,4), (-1, 2, -2, -1,4)];M= matrix(m)
78
sage: M
79
[ 1 -2 -1 -1 9]
80
[ 1 8 6 2 2]
81
[ 1 1 -1 1 4]
82
[-1 2 -2 -1 4]
83
84
Get the 2 x 2 submatrix of M, starting at row index and column index 1::
85
86
sage: M[1:3,1:3]
87
[ 8 6]
88
[ 1 -1]
89
90
Get the 2 x 3 submatrix of M starting at row index and column index 1::
91
92
sage: M[1:3,[1..3]]
93
[ 8 6 2]
94
[ 1 -1 1]
95
96
Get the second column of M::
97
98
sage: M[:,1]
99
[-2]
100
[ 8]
101
[ 1]
102
[ 2]
103
104
Get the first row of M::
105
106
sage: M[0,:]
107
[ 1 -2 -1 -1 9]
108
109
Get the last row of M (negative numbers count from the end)::
110
111
sage: M[-1,:]
112
[-1 2 -2 -1 4]
113
114
More examples::
115
116
sage: M[range(2),:]
117
[ 1 -2 -1 -1 9]
118
[ 1 8 6 2 2]
119
sage: M[range(2),4]
120
[9]
121
[2]
122
sage: M[range(3),range(5)]
123
[ 1 -2 -1 -1 9]
124
[ 1 8 6 2 2]
125
[ 1 1 -1 1 4]
126
127
sage: M[3,range(5)]
128
[-1 2 -2 -1 4]
129
sage: M[3,:]
130
[-1 2 -2 -1 4]
131
sage: M[3,4]
132
4
133
134
sage: M[-1,:]
135
[-1 2 -2 -1 4]
136
137
sage: A = matrix(ZZ,3,4, [3, 2, -5, 0, 1, -1, 1, -4, 1, 0, 1, -3]); A
138
[ 3 2 -5 0]
139
[ 1 -1 1 -4]
140
[ 1 0 1 -3]
141
142
A series of three numbers, separated by colons, like ``n:m:s``, means
143
numbers from ``n`` up to (but not including) ``m``, in steps of ``s``.
144
So ``0:5:2`` means the sequence ``[0,2,4]``::
145
146
sage: A[:,0:4:2]
147
[ 3 -5]
148
[ 1 1]
149
[ 1 1]
150
151
sage: A[1:,0:4:2]
152
[1 1]
153
[1 1]
154
155
sage: A[2::-1,:]
156
[ 1 0 1 -3]
157
[ 1 -1 1 -4]
158
[ 3 2 -5 0]
159
160
sage: A[1:,3::-1]
161
[-4 1 -1 1]
162
[-3 1 0 1]
163
164
sage: A[1:,3::-2]
165
[-4 -1]
166
[-3 0]
167
168
sage: A[2::-1,3:1:-1]
169
[-3 1]
170
[-4 1]
171
[ 0 -5]
172
173
We can also change submatrices using these indexing features::
174
175
sage: M=matrix([(1, -2, -1, -1,9), (1, 8, 6, 2,2), (1, 1, -1, 1,4), (-1, 2, -2, -1,4)]); M
176
[ 1 -2 -1 -1 9]
177
[ 1 8 6 2 2]
178
[ 1 1 -1 1 4]
179
[-1 2 -2 -1 4]
180
181
Set the 2 x 2 submatrix of M, starting at row index and column index 1::
182
183
sage: M[1:3,1:3] = [[1,0],[0,1]]; M
184
[ 1 -2 -1 -1 9]
185
[ 1 1 0 2 2]
186
[ 1 0 1 1 4]
187
[-1 2 -2 -1 4]
188
189
Set the 2 x 3 submatrix of M starting at row index and column index 1::
190
191
sage: M[1:3,[1..3]] = M[2:4,0:3]; M
192
[ 1 -2 -1 -1 9]
193
[ 1 1 0 1 2]
194
[ 1 -1 2 -2 4]
195
[-1 2 -2 -1 4]
196
197
Set part of the first column of M::
198
199
sage: M[1:,0]=[[2],[3],[4]]; M
200
[ 1 -2 -1 -1 9]
201
[ 2 1 0 1 2]
202
[ 3 -1 2 -2 4]
203
[ 4 2 -2 -1 4]
204
205
Or do a similar thing with a vector::
206
207
sage: M[1:,0]=vector([-2,-3,-4]); M
208
[ 1 -2 -1 -1 9]
209
[-2 1 0 1 2]
210
[-3 -1 2 -2 4]
211
[-4 2 -2 -1 4]
212
213
Or a constant::
214
215
sage: M[1:,0]=30; M
216
[ 1 -2 -1 -1 9]
217
[30 1 0 1 2]
218
[30 -1 2 -2 4]
219
[30 2 -2 -1 4]
220
221
222
Set the first row of M::
223
224
sage: M[0,:]=[[20,21,22,23,24]]; M
225
[20 21 22 23 24]
226
[30 1 0 1 2]
227
[30 -1 2 -2 4]
228
[30 2 -2 -1 4]
229
sage: M[0,:]=vector([0,1,2,3,4]); M
230
[ 0 1 2 3 4]
231
[30 1 0 1 2]
232
[30 -1 2 -2 4]
233
[30 2 -2 -1 4]
234
sage: M[0,:]=-3; M
235
[-3 -3 -3 -3 -3]
236
[30 1 0 1 2]
237
[30 -1 2 -2 4]
238
[30 2 -2 -1 4]
239
240
241
sage: A = matrix(ZZ,3,4, [3, 2, -5, 0, 1, -1, 1, -4, 1, 0, 1, -3]); A
242
[ 3 2 -5 0]
243
[ 1 -1 1 -4]
244
[ 1 0 1 -3]
245
246
We can use the step feature of slices to set every other column::
247
248
sage: A[:,0:3:2] = 5; A
249
[ 5 2 5 0]
250
[ 5 -1 5 -4]
251
[ 5 0 5 -3]
252
253
sage: A[1:,0:4:2] = [[100,200],[300,400]]; A
254
[ 5 2 5 0]
255
[100 -1 200 -4]
256
[300 0 400 -3]
257
258
We can also count backwards to flip the matrix upside down::
259
260
sage: A[::-1,:]=A; A
261
[300 0 400 -3]
262
[100 -1 200 -4]
263
[ 5 2 5 0]
264
265
266
sage: A[1:,3::-1]=[[2,3,0,1],[9,8,7,6]]; A
267
[300 0 400 -3]
268
[ 1 0 3 2]
269
[ 6 7 8 9]
270
271
sage: A[1:,::-2] = A[1:,::2]; A
272
[300 0 400 -3]
273
[ 1 3 3 1]
274
[ 6 8 8 6]
275
276
sage: A[::-1,3:1:-1] = [[4,3],[1,2],[-1,-2]]; A
277
[300 0 -2 -1]
278
[ 1 3 2 1]
279
[ 6 8 3 4]
280
281
282
283
We save and load a matrix::
284
285
sage: A = matrix(Integers(8),3,range(9))
286
sage: loads(dumps(A)) == A
287
True
288
289
MUTABILITY: Matrices are either immutable or not. When initially
290
created, matrices are typically mutable, so one can change their
291
entries. Once a matrix `A` is made immutable using
292
``A.set_immutable()`` the entries of `A`
293
cannot be changed, and `A` can never be made mutable again.
294
However, properties of `A` such as its rank, characteristic
295
polynomial, etc., are all cached so computations involving
296
`A` may be more efficient. Once `A` is made
297
immutable it cannot be changed back. However, one can obtain a
298
mutable copy of `A` using ``copy(A)``.
299
300
EXAMPLES::
301
302
sage: A = matrix(RR,2,[1,10,3.5,2])
303
sage: A.set_immutable()
304
sage: copy(A) is A
305
False
306
307
The echelon form method always returns immutable matrices with
308
known rank.
309
310
EXAMPLES::
311
312
sage: A = matrix(Integers(8),3,range(9))
313
sage: A.determinant()
314
0
315
sage: A[0,0] = 5
316
sage: A.determinant()
317
1
318
sage: A.set_immutable()
319
sage: A[0,0] = 5
320
Traceback (most recent call last):
321
...
322
ValueError: matrix is immutable; please change a copy instead (i.e., use copy(M) to change a copy of M).
323
324
Implementation and Design
325
-------------------------
326
327
Class Diagram (an x means that class is currently supported)::
328
329
x Matrix
330
x Matrix_sparse
331
x Matrix_generic_sparse
332
x Matrix_integer_sparse
333
x Matrix_rational_sparse
334
Matrix_cyclo_sparse
335
x Matrix_modn_sparse
336
Matrix_RR_sparse
337
Matrix_CC_sparse
338
Matrix_RDF_sparse
339
Matrix_CDF_sparse
340
341
x Matrix_dense
342
x Matrix_generic_dense
343
x Matrix_integer_dense
344
Matrix_integer_2x2_dense
345
x Matrix_rational_dense
346
Matrix_cyclo_dense -- idea: restrict scalars to QQ, compute charpoly there, then factor
347
x Matrix_modn_dense
348
Matrix_RR_dense
349
Matrix_CC_dense
350
x Matrix_real_double_dense
351
x Matrix_complex_double_dense
352
353
The corresponding files in the sage/matrix library code directory
354
are named
355
356
::
357
358
[matrix] [base ring] [dense or sparse].
359
360
See the files ``matrix_template.pxd`` and
361
``matrix_template.pyx``.
362
363
::
364
365
New matrices types can only be implemented in Cython.
366
367
*********** LEVEL 1 **********
368
NON-OPTIONAL
369
For each base field it is *absolutely* essential to completely
370
implement the following functionality for that base ring:
371
372
* __cinit__ -- should use sage_malloc from ext/stdsage.pxi (only
373
needed if allocate memory)
374
* __init__ -- this signature: 'def __init__(self, parent, entries, copy, coerce)'
375
* __dealloc__ -- use sage_free (only needed if allocate memory)
376
* set_unsafe(self, size_t i, size_t j, x) -- doesn't do bounds or any other checks; assumes x is in self._base_ring
377
* get_unsafe(self, size_t i, size_t j) -- doesn't do checks
378
* __richcmp__ -- always the same (I don't know why its needed -- bug in PYREX).
379
380
Note that the __init__ function must construct the all zero matrix if ``entries == None``.
381
382
*********** LEVEL 2 **********
383
384
IMPORTANT (and *highly* recommended):
385
386
After getting the special class with all level 1 functionality to
387
work, implement all of the following (they should not change
388
functionality, except speed (always faster!) in any way):
389
390
* def _pickle(self):
391
return data, version
392
* def _unpickle(self, data, int version)
393
reconstruct matrix from given data and version; may assume _parent, _nrows, and _ncols are set.
394
Use version numbers >= 0 so if you change the pickle strategy then
395
old objects still unpickle.
396
* cdef _list -- list of underlying elements (need not be a copy)
397
* cdef _dict -- sparse dictionary of underlying elements
398
* cdef _add_ -- add two matrices with identical parents
399
* _matrix_times_matrix_c_impl -- multiply two matrices with compatible dimensions and
400
identical base rings (both sparse or both dense)
401
* cdef _cmp_c_impl -- compare two matrices with identical parents
402
* cdef _lmul_c_impl -- multiply this matrix on the right by a scalar, i.e., self * scalar
403
* cdef _rmul_c_impl -- multiply this matrix on the left by a scalar, i.e., scalar * self
404
* __copy__
405
* __neg__
406
407
The list and dict returned by _list and _dict will *not* be changed
408
by any internal algorithms and are not accessible to the user.
409
410
*********** LEVEL 3 **********
411
OPTIONAL:
412
413
* cdef _sub_
414
* __invert__
415
* _multiply_classical
416
* __deepcopy__
417
418
Further special support:
419
* Matrix windows -- to support Strassen multiplication for a given base ring.
420
* Other functions, e.g., transpose, for which knowing the
421
specific representation can be helpful.
422
423
.. note::
424
425
- For caching, use self.fetch and self.cache.
426
427
- Any method that can change the matrix should call
428
``check_mutability()`` first. There are also many fast cdef'd bounds checking methods.
429
430
- Kernels of matrices
431
Implement only a left_kernel() or right_kernel() method, whichever requires
432
the least overhead (usually meaning little or no transposing). Let the
433
methods in the matrix2 class handle left, right, generic kernel distinctions.
434
"""
435
436