Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/numpy/matrixlib/defmatrix.py: 25%
238 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-09 06:12 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-09 06:12 +0000
1__all__ = ['matrix', 'bmat', 'asmatrix']
3import sys
4import warnings
5import ast
7from .._utils import set_module
8import numpy._core.numeric as N
9from numpy._core.numeric import concatenate, isscalar
10# While not in __all__, matrix_power used to be defined here, so we import
11# it for backward compatibility.
12from numpy.linalg import matrix_power
15def _convert_from_string(data):
16 for char in '[]':
17 data = data.replace(char, '')
19 rows = data.split(';')
20 newdata = []
21 count = 0
22 for row in rows:
23 trow = row.split(',')
24 newrow = []
25 for col in trow:
26 temp = col.split()
27 newrow.extend(map(ast.literal_eval, temp))
28 if count == 0:
29 Ncols = len(newrow)
30 elif len(newrow) != Ncols:
31 raise ValueError("Rows not the same size.")
32 count += 1
33 newdata.append(newrow)
34 return newdata
37@set_module('numpy')
38def asmatrix(data, dtype=None):
39 """
40 Interpret the input as a matrix.
42 Unlike `matrix`, `asmatrix` does not make a copy if the input is already
43 a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``.
45 Parameters
46 ----------
47 data : array_like
48 Input data.
49 dtype : data-type
50 Data-type of the output matrix.
52 Returns
53 -------
54 mat : matrix
55 `data` interpreted as a matrix.
57 Examples
58 --------
59 >>> x = np.array([[1, 2], [3, 4]])
61 >>> m = np.asmatrix(x)
63 >>> x[0,0] = 5
65 >>> m
66 matrix([[5, 2],
67 [3, 4]])
69 """
70 return matrix(data, dtype=dtype, copy=False)
73@set_module('numpy')
74class matrix(N.ndarray):
75 """
76 matrix(data, dtype=None, copy=True)
78 Returns a matrix from an array-like object, or from a string of data.
80 A matrix is a specialized 2-D array that retains its 2-D nature
81 through operations. It has certain special operators, such as ``*``
82 (matrix multiplication) and ``**`` (matrix power).
84 .. note:: It is no longer recommended to use this class, even for linear
85 algebra. Instead use regular arrays. The class may be removed
86 in the future.
88 Parameters
89 ----------
90 data : array_like or string
91 If `data` is a string, it is interpreted as a matrix with commas
92 or spaces separating columns, and semicolons separating rows.
93 dtype : data-type
94 Data-type of the output matrix.
95 copy : bool
96 If `data` is already an `ndarray`, then this flag determines
97 whether the data is copied (the default), or whether a view is
98 constructed.
100 See Also
101 --------
102 array
104 Examples
105 --------
106 >>> a = np.matrix('1 2; 3 4')
107 >>> a
108 matrix([[1, 2],
109 [3, 4]])
111 >>> np.matrix([[1, 2], [3, 4]])
112 matrix([[1, 2],
113 [3, 4]])
115 """
116 __array_priority__ = 10.0
117 def __new__(subtype, data, dtype=None, copy=True):
118 warnings.warn('the matrix subclass is not the recommended way to '
119 'represent matrices or deal with linear algebra (see '
120 'https://docs.scipy.org/doc/numpy/user/'
121 'numpy-for-matlab-users.html). '
122 'Please adjust your code to use regular ndarray.',
123 PendingDeprecationWarning, stacklevel=2)
124 if isinstance(data, matrix):
125 dtype2 = data.dtype
126 if (dtype is None):
127 dtype = dtype2
128 if (dtype2 == dtype) and (not copy):
129 return data
130 return data.astype(dtype)
132 if isinstance(data, N.ndarray):
133 if dtype is None:
134 intype = data.dtype
135 else:
136 intype = N.dtype(dtype)
137 new = data.view(subtype)
138 if intype != data.dtype:
139 return new.astype(intype)
140 if copy: return new.copy()
141 else: return new
143 if isinstance(data, str):
144 data = _convert_from_string(data)
146 # now convert data to an array
147 copy = None if not copy else True
148 arr = N.array(data, dtype=dtype, copy=copy)
149 ndim = arr.ndim
150 shape = arr.shape
151 if (ndim > 2):
152 raise ValueError("matrix must be 2-dimensional")
153 elif ndim == 0:
154 shape = (1, 1)
155 elif ndim == 1:
156 shape = (1, shape[0])
158 order = 'C'
159 if (ndim == 2) and arr.flags.fortran:
160 order = 'F'
162 if not (order or arr.flags.contiguous):
163 arr = arr.copy()
165 ret = N.ndarray.__new__(subtype, shape, arr.dtype,
166 buffer=arr,
167 order=order)
168 return ret
170 def __array_finalize__(self, obj):
171 self._getitem = False
172 if (isinstance(obj, matrix) and obj._getitem): return
173 ndim = self.ndim
174 if (ndim == 2):
175 return
176 if (ndim > 2):
177 newshape = tuple([x for x in self.shape if x > 1])
178 ndim = len(newshape)
179 if ndim == 2:
180 self.shape = newshape
181 return
182 elif (ndim > 2):
183 raise ValueError("shape too large to be a matrix.")
184 else:
185 newshape = self.shape
186 if ndim == 0:
187 self.shape = (1, 1)
188 elif ndim == 1:
189 self.shape = (1, newshape[0])
190 return
192 def __getitem__(self, index):
193 self._getitem = True
195 try:
196 out = N.ndarray.__getitem__(self, index)
197 finally:
198 self._getitem = False
200 if not isinstance(out, N.ndarray):
201 return out
203 if out.ndim == 0:
204 return out[()]
205 if out.ndim == 1:
206 sh = out.shape[0]
207 # Determine when we should have a column array
208 try:
209 n = len(index)
210 except Exception:
211 n = 0
212 if n > 1 and isscalar(index[1]):
213 out.shape = (sh, 1)
214 else:
215 out.shape = (1, sh)
216 return out
218 def __mul__(self, other):
219 if isinstance(other, (N.ndarray, list, tuple)) :
220 # This promotes 1-D vectors to row vectors
221 return N.dot(self, asmatrix(other))
222 if isscalar(other) or not hasattr(other, '__rmul__') :
223 return N.dot(self, other)
224 return NotImplemented
226 def __rmul__(self, other):
227 return N.dot(other, self)
229 def __imul__(self, other):
230 self[:] = self * other
231 return self
233 def __pow__(self, other):
234 return matrix_power(self, other)
236 def __ipow__(self, other):
237 self[:] = self ** other
238 return self
240 def __rpow__(self, other):
241 return NotImplemented
243 def _align(self, axis):
244 """A convenience function for operations that need to preserve axis
245 orientation.
246 """
247 if axis is None:
248 return self[0, 0]
249 elif axis==0:
250 return self
251 elif axis==1:
252 return self.transpose()
253 else:
254 raise ValueError("unsupported axis")
256 def _collapse(self, axis):
257 """A convenience function for operations that want to collapse
258 to a scalar like _align, but are using keepdims=True
259 """
260 if axis is None:
261 return self[0, 0]
262 else:
263 return self
265 # Necessary because base-class tolist expects dimension
266 # reduction by x[0]
267 def tolist(self):
268 """
269 Return the matrix as a (possibly nested) list.
271 See `ndarray.tolist` for full documentation.
273 See Also
274 --------
275 ndarray.tolist
277 Examples
278 --------
279 >>> x = np.matrix(np.arange(12).reshape((3,4))); x
280 matrix([[ 0, 1, 2, 3],
281 [ 4, 5, 6, 7],
282 [ 8, 9, 10, 11]])
283 >>> x.tolist()
284 [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
286 """
287 return self.__array__().tolist()
289 # To preserve orientation of result...
290 def sum(self, axis=None, dtype=None, out=None):
291 """
292 Returns the sum of the matrix elements, along the given axis.
294 Refer to `numpy.sum` for full documentation.
296 See Also
297 --------
298 numpy.sum
300 Notes
301 -----
302 This is the same as `ndarray.sum`, except that where an `ndarray` would
303 be returned, a `matrix` object is returned instead.
305 Examples
306 --------
307 >>> x = np.matrix([[1, 2], [4, 3]])
308 >>> x.sum()
309 10
310 >>> x.sum(axis=1)
311 matrix([[3],
312 [7]])
313 >>> x.sum(axis=1, dtype='float')
314 matrix([[3.],
315 [7.]])
316 >>> out = np.zeros((2, 1), dtype='float')
317 >>> x.sum(axis=1, dtype='float', out=np.asmatrix(out))
318 matrix([[3.],
319 [7.]])
321 """
322 return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis)
325 # To update docstring from array to matrix...
326 def squeeze(self, axis=None):
327 """
328 Return a possibly reshaped matrix.
330 Refer to `numpy.squeeze` for more documentation.
332 Parameters
333 ----------
334 axis : None or int or tuple of ints, optional
335 Selects a subset of the axes of length one in the shape.
336 If an axis is selected with shape entry greater than one,
337 an error is raised.
339 Returns
340 -------
341 squeezed : matrix
342 The matrix, but as a (1, N) matrix if it had shape (N, 1).
344 See Also
345 --------
346 numpy.squeeze : related function
348 Notes
349 -----
350 If `m` has a single column then that column is returned
351 as the single row of a matrix. Otherwise `m` is returned.
352 The returned matrix is always either `m` itself or a view into `m`.
353 Supplying an axis keyword argument will not affect the returned matrix
354 but it may cause an error to be raised.
356 Examples
357 --------
358 >>> c = np.matrix([[1], [2]])
359 >>> c
360 matrix([[1],
361 [2]])
362 >>> c.squeeze()
363 matrix([[1, 2]])
364 >>> r = c.T
365 >>> r
366 matrix([[1, 2]])
367 >>> r.squeeze()
368 matrix([[1, 2]])
369 >>> m = np.matrix([[1, 2], [3, 4]])
370 >>> m.squeeze()
371 matrix([[1, 2],
372 [3, 4]])
374 """
375 return N.ndarray.squeeze(self, axis=axis)
378 # To update docstring from array to matrix...
379 def flatten(self, order='C'):
380 """
381 Return a flattened copy of the matrix.
383 All `N` elements of the matrix are placed into a single row.
385 Parameters
386 ----------
387 order : {'C', 'F', 'A', 'K'}, optional
388 'C' means to flatten in row-major (C-style) order. 'F' means to
389 flatten in column-major (Fortran-style) order. 'A' means to
390 flatten in column-major order if `m` is Fortran *contiguous* in
391 memory, row-major order otherwise. 'K' means to flatten `m` in
392 the order the elements occur in memory. The default is 'C'.
394 Returns
395 -------
396 y : matrix
397 A copy of the matrix, flattened to a `(1, N)` matrix where `N`
398 is the number of elements in the original matrix.
400 See Also
401 --------
402 ravel : Return a flattened array.
403 flat : A 1-D flat iterator over the matrix.
405 Examples
406 --------
407 >>> m = np.matrix([[1,2], [3,4]])
408 >>> m.flatten()
409 matrix([[1, 2, 3, 4]])
410 >>> m.flatten('F')
411 matrix([[1, 3, 2, 4]])
413 """
414 return N.ndarray.flatten(self, order=order)
416 def mean(self, axis=None, dtype=None, out=None):
417 """
418 Returns the average of the matrix elements along the given axis.
420 Refer to `numpy.mean` for full documentation.
422 See Also
423 --------
424 numpy.mean
426 Notes
427 -----
428 Same as `ndarray.mean` except that, where that returns an `ndarray`,
429 this returns a `matrix` object.
431 Examples
432 --------
433 >>> x = np.matrix(np.arange(12).reshape((3, 4)))
434 >>> x
435 matrix([[ 0, 1, 2, 3],
436 [ 4, 5, 6, 7],
437 [ 8, 9, 10, 11]])
438 >>> x.mean()
439 5.5
440 >>> x.mean(0)
441 matrix([[4., 5., 6., 7.]])
442 >>> x.mean(1)
443 matrix([[ 1.5],
444 [ 5.5],
445 [ 9.5]])
447 """
448 return N.ndarray.mean(self, axis, dtype, out, keepdims=True)._collapse(axis)
450 def std(self, axis=None, dtype=None, out=None, ddof=0):
451 """
452 Return the standard deviation of the array elements along the given axis.
454 Refer to `numpy.std` for full documentation.
456 See Also
457 --------
458 numpy.std
460 Notes
461 -----
462 This is the same as `ndarray.std`, except that where an `ndarray` would
463 be returned, a `matrix` object is returned instead.
465 Examples
466 --------
467 >>> x = np.matrix(np.arange(12).reshape((3, 4)))
468 >>> x
469 matrix([[ 0, 1, 2, 3],
470 [ 4, 5, 6, 7],
471 [ 8, 9, 10, 11]])
472 >>> x.std()
473 3.4520525295346629 # may vary
474 >>> x.std(0)
475 matrix([[ 3.26598632, 3.26598632, 3.26598632, 3.26598632]]) # may vary
476 >>> x.std(1)
477 matrix([[ 1.11803399],
478 [ 1.11803399],
479 [ 1.11803399]])
481 """
482 return N.ndarray.std(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis)
484 def var(self, axis=None, dtype=None, out=None, ddof=0):
485 """
486 Returns the variance of the matrix elements, along the given axis.
488 Refer to `numpy.var` for full documentation.
490 See Also
491 --------
492 numpy.var
494 Notes
495 -----
496 This is the same as `ndarray.var`, except that where an `ndarray` would
497 be returned, a `matrix` object is returned instead.
499 Examples
500 --------
501 >>> x = np.matrix(np.arange(12).reshape((3, 4)))
502 >>> x
503 matrix([[ 0, 1, 2, 3],
504 [ 4, 5, 6, 7],
505 [ 8, 9, 10, 11]])
506 >>> x.var()
507 11.916666666666666
508 >>> x.var(0)
509 matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) # may vary
510 >>> x.var(1)
511 matrix([[1.25],
512 [1.25],
513 [1.25]])
515 """
516 return N.ndarray.var(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis)
518 def prod(self, axis=None, dtype=None, out=None):
519 """
520 Return the product of the array elements over the given axis.
522 Refer to `prod` for full documentation.
524 See Also
525 --------
526 prod, ndarray.prod
528 Notes
529 -----
530 Same as `ndarray.prod`, except, where that returns an `ndarray`, this
531 returns a `matrix` object instead.
533 Examples
534 --------
535 >>> x = np.matrix(np.arange(12).reshape((3,4))); x
536 matrix([[ 0, 1, 2, 3],
537 [ 4, 5, 6, 7],
538 [ 8, 9, 10, 11]])
539 >>> x.prod()
540 0
541 >>> x.prod(0)
542 matrix([[ 0, 45, 120, 231]])
543 >>> x.prod(1)
544 matrix([[ 0],
545 [ 840],
546 [7920]])
548 """
549 return N.ndarray.prod(self, axis, dtype, out, keepdims=True)._collapse(axis)
551 def any(self, axis=None, out=None):
552 """
553 Test whether any array element along a given axis evaluates to True.
555 Refer to `numpy.any` for full documentation.
557 Parameters
558 ----------
559 axis : int, optional
560 Axis along which logical OR is performed
561 out : ndarray, optional
562 Output to existing array instead of creating new one, must have
563 same shape as expected output
565 Returns
566 -------
567 any : bool, ndarray
568 Returns a single bool if `axis` is ``None``; otherwise,
569 returns `ndarray`
571 """
572 return N.ndarray.any(self, axis, out, keepdims=True)._collapse(axis)
574 def all(self, axis=None, out=None):
575 """
576 Test whether all matrix elements along a given axis evaluate to True.
578 Parameters
579 ----------
580 See `numpy.all` for complete descriptions
582 See Also
583 --------
584 numpy.all
586 Notes
587 -----
588 This is the same as `ndarray.all`, but it returns a `matrix` object.
590 Examples
591 --------
592 >>> x = np.matrix(np.arange(12).reshape((3,4))); x
593 matrix([[ 0, 1, 2, 3],
594 [ 4, 5, 6, 7],
595 [ 8, 9, 10, 11]])
596 >>> y = x[0]; y
597 matrix([[0, 1, 2, 3]])
598 >>> (x == y)
599 matrix([[ True, True, True, True],
600 [False, False, False, False],
601 [False, False, False, False]])
602 >>> (x == y).all()
603 False
604 >>> (x == y).all(0)
605 matrix([[False, False, False, False]])
606 >>> (x == y).all(1)
607 matrix([[ True],
608 [False],
609 [False]])
611 """
612 return N.ndarray.all(self, axis, out, keepdims=True)._collapse(axis)
614 def max(self, axis=None, out=None):
615 """
616 Return the maximum value along an axis.
618 Parameters
619 ----------
620 See `amax` for complete descriptions
622 See Also
623 --------
624 amax, ndarray.max
626 Notes
627 -----
628 This is the same as `ndarray.max`, but returns a `matrix` object
629 where `ndarray.max` would return an ndarray.
631 Examples
632 --------
633 >>> x = np.matrix(np.arange(12).reshape((3,4))); x
634 matrix([[ 0, 1, 2, 3],
635 [ 4, 5, 6, 7],
636 [ 8, 9, 10, 11]])
637 >>> x.max()
638 11
639 >>> x.max(0)
640 matrix([[ 8, 9, 10, 11]])
641 >>> x.max(1)
642 matrix([[ 3],
643 [ 7],
644 [11]])
646 """
647 return N.ndarray.max(self, axis, out, keepdims=True)._collapse(axis)
649 def argmax(self, axis=None, out=None):
650 """
651 Indexes of the maximum values along an axis.
653 Return the indexes of the first occurrences of the maximum values
654 along the specified axis. If axis is None, the index is for the
655 flattened matrix.
657 Parameters
658 ----------
659 See `numpy.argmax` for complete descriptions
661 See Also
662 --------
663 numpy.argmax
665 Notes
666 -----
667 This is the same as `ndarray.argmax`, but returns a `matrix` object
668 where `ndarray.argmax` would return an `ndarray`.
670 Examples
671 --------
672 >>> x = np.matrix(np.arange(12).reshape((3,4))); x
673 matrix([[ 0, 1, 2, 3],
674 [ 4, 5, 6, 7],
675 [ 8, 9, 10, 11]])
676 >>> x.argmax()
677 11
678 >>> x.argmax(0)
679 matrix([[2, 2, 2, 2]])
680 >>> x.argmax(1)
681 matrix([[3],
682 [3],
683 [3]])
685 """
686 return N.ndarray.argmax(self, axis, out)._align(axis)
688 def min(self, axis=None, out=None):
689 """
690 Return the minimum value along an axis.
692 Parameters
693 ----------
694 See `amin` for complete descriptions.
696 See Also
697 --------
698 amin, ndarray.min
700 Notes
701 -----
702 This is the same as `ndarray.min`, but returns a `matrix` object
703 where `ndarray.min` would return an ndarray.
705 Examples
706 --------
707 >>> x = -np.matrix(np.arange(12).reshape((3,4))); x
708 matrix([[ 0, -1, -2, -3],
709 [ -4, -5, -6, -7],
710 [ -8, -9, -10, -11]])
711 >>> x.min()
712 -11
713 >>> x.min(0)
714 matrix([[ -8, -9, -10, -11]])
715 >>> x.min(1)
716 matrix([[ -3],
717 [ -7],
718 [-11]])
720 """
721 return N.ndarray.min(self, axis, out, keepdims=True)._collapse(axis)
723 def argmin(self, axis=None, out=None):
724 """
725 Indexes of the minimum values along an axis.
727 Return the indexes of the first occurrences of the minimum values
728 along the specified axis. If axis is None, the index is for the
729 flattened matrix.
731 Parameters
732 ----------
733 See `numpy.argmin` for complete descriptions.
735 See Also
736 --------
737 numpy.argmin
739 Notes
740 -----
741 This is the same as `ndarray.argmin`, but returns a `matrix` object
742 where `ndarray.argmin` would return an `ndarray`.
744 Examples
745 --------
746 >>> x = -np.matrix(np.arange(12).reshape((3,4))); x
747 matrix([[ 0, -1, -2, -3],
748 [ -4, -5, -6, -7],
749 [ -8, -9, -10, -11]])
750 >>> x.argmin()
751 11
752 >>> x.argmin(0)
753 matrix([[2, 2, 2, 2]])
754 >>> x.argmin(1)
755 matrix([[3],
756 [3],
757 [3]])
759 """
760 return N.ndarray.argmin(self, axis, out)._align(axis)
762 def ptp(self, axis=None, out=None):
763 """
764 Peak-to-peak (maximum - minimum) value along the given axis.
766 Refer to `numpy.ptp` for full documentation.
768 See Also
769 --------
770 numpy.ptp
772 Notes
773 -----
774 Same as `ndarray.ptp`, except, where that would return an `ndarray` object,
775 this returns a `matrix` object.
777 Examples
778 --------
779 >>> x = np.matrix(np.arange(12).reshape((3,4))); x
780 matrix([[ 0, 1, 2, 3],
781 [ 4, 5, 6, 7],
782 [ 8, 9, 10, 11]])
783 >>> x.ptp()
784 11
785 >>> x.ptp(0)
786 matrix([[8, 8, 8, 8]])
787 >>> x.ptp(1)
788 matrix([[3],
789 [3],
790 [3]])
792 """
793 return N.ptp(self, axis, out)._align(axis)
795 @property
796 def I(self):
797 """
798 Returns the (multiplicative) inverse of invertible `self`.
800 Parameters
801 ----------
802 None
804 Returns
805 -------
806 ret : matrix object
807 If `self` is non-singular, `ret` is such that ``ret * self`` ==
808 ``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return
809 ``True``.
811 Raises
812 ------
813 numpy.linalg.LinAlgError: Singular matrix
814 If `self` is singular.
816 See Also
817 --------
818 linalg.inv
820 Examples
821 --------
822 >>> m = np.matrix('[1, 2; 3, 4]'); m
823 matrix([[1, 2],
824 [3, 4]])
825 >>> m.getI()
826 matrix([[-2. , 1. ],
827 [ 1.5, -0.5]])
828 >>> m.getI() * m
829 matrix([[ 1., 0.], # may vary
830 [ 0., 1.]])
832 """
833 M, N = self.shape
834 if M == N:
835 from numpy.linalg import inv as func
836 else:
837 from numpy.linalg import pinv as func
838 return asmatrix(func(self))
840 @property
841 def A(self):
842 """
843 Return `self` as an `ndarray` object.
845 Equivalent to ``np.asarray(self)``.
847 Parameters
848 ----------
849 None
851 Returns
852 -------
853 ret : ndarray
854 `self` as an `ndarray`
856 Examples
857 --------
858 >>> x = np.matrix(np.arange(12).reshape((3,4))); x
859 matrix([[ 0, 1, 2, 3],
860 [ 4, 5, 6, 7],
861 [ 8, 9, 10, 11]])
862 >>> x.getA()
863 array([[ 0, 1, 2, 3],
864 [ 4, 5, 6, 7],
865 [ 8, 9, 10, 11]])
867 """
868 return self.__array__()
870 @property
871 def A1(self):
872 """
873 Return `self` as a flattened `ndarray`.
875 Equivalent to ``np.asarray(x).ravel()``
877 Parameters
878 ----------
879 None
881 Returns
882 -------
883 ret : ndarray
884 `self`, 1-D, as an `ndarray`
886 Examples
887 --------
888 >>> x = np.matrix(np.arange(12).reshape((3,4))); x
889 matrix([[ 0, 1, 2, 3],
890 [ 4, 5, 6, 7],
891 [ 8, 9, 10, 11]])
892 >>> x.getA1()
893 array([ 0, 1, 2, ..., 9, 10, 11])
896 """
897 return self.__array__().ravel()
900 def ravel(self, order='C'):
901 """
902 Return a flattened matrix.
904 Refer to `numpy.ravel` for more documentation.
906 Parameters
907 ----------
908 order : {'C', 'F', 'A', 'K'}, optional
909 The elements of `m` are read using this index order. 'C' means to
910 index the elements in C-like order, with the last axis index
911 changing fastest, back to the first axis index changing slowest.
912 'F' means to index the elements in Fortran-like index order, with
913 the first index changing fastest, and the last index changing
914 slowest. Note that the 'C' and 'F' options take no account of the
915 memory layout of the underlying array, and only refer to the order
916 of axis indexing. 'A' means to read the elements in Fortran-like
917 index order if `m` is Fortran *contiguous* in memory, C-like order
918 otherwise. 'K' means to read the elements in the order they occur
919 in memory, except for reversing the data when strides are negative.
920 By default, 'C' index order is used.
922 Returns
923 -------
924 ret : matrix
925 Return the matrix flattened to shape `(1, N)` where `N`
926 is the number of elements in the original matrix.
927 A copy is made only if necessary.
929 See Also
930 --------
931 matrix.flatten : returns a similar output matrix but always a copy
932 matrix.flat : a flat iterator on the array.
933 numpy.ravel : related function which returns an ndarray
935 """
936 return N.ndarray.ravel(self, order=order)
938 @property
939 def T(self):
940 """
941 Returns the transpose of the matrix.
943 Does *not* conjugate! For the complex conjugate transpose, use ``.H``.
945 Parameters
946 ----------
947 None
949 Returns
950 -------
951 ret : matrix object
952 The (non-conjugated) transpose of the matrix.
954 See Also
955 --------
956 transpose, getH
958 Examples
959 --------
960 >>> m = np.matrix('[1, 2; 3, 4]')
961 >>> m
962 matrix([[1, 2],
963 [3, 4]])
964 >>> m.getT()
965 matrix([[1, 3],
966 [2, 4]])
968 """
969 return self.transpose()
971 @property
972 def H(self):
973 """
974 Returns the (complex) conjugate transpose of `self`.
976 Equivalent to ``np.transpose(self)`` if `self` is real-valued.
978 Parameters
979 ----------
980 None
982 Returns
983 -------
984 ret : matrix object
985 complex conjugate transpose of `self`
987 Examples
988 --------
989 >>> x = np.matrix(np.arange(12).reshape((3,4)))
990 >>> z = x - 1j*x; z
991 matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j],
992 [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j],
993 [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]])
994 >>> z.getH()
995 matrix([[ 0. -0.j, 4. +4.j, 8. +8.j],
996 [ 1. +1.j, 5. +5.j, 9. +9.j],
997 [ 2. +2.j, 6. +6.j, 10.+10.j],
998 [ 3. +3.j, 7. +7.j, 11.+11.j]])
1000 """
1001 if issubclass(self.dtype.type, N.complexfloating):
1002 return self.transpose().conjugate()
1003 else:
1004 return self.transpose()
1006 # kept for compatibility
1007 getT = T.fget
1008 getA = A.fget
1009 getA1 = A1.fget
1010 getH = H.fget
1011 getI = I.fget
1013def _from_string(str, gdict, ldict):
1014 rows = str.split(';')
1015 rowtup = []
1016 for row in rows:
1017 trow = row.split(',')
1018 newrow = []
1019 for x in trow:
1020 newrow.extend(x.split())
1021 trow = newrow
1022 coltup = []
1023 for col in trow:
1024 col = col.strip()
1025 try:
1026 thismat = ldict[col]
1027 except KeyError:
1028 try:
1029 thismat = gdict[col]
1030 except KeyError as e:
1031 raise NameError(f"name {col!r} is not defined") from None
1033 coltup.append(thismat)
1034 rowtup.append(concatenate(coltup, axis=-1))
1035 return concatenate(rowtup, axis=0)
1038@set_module('numpy')
1039def bmat(obj, ldict=None, gdict=None):
1040 """
1041 Build a matrix object from a string, nested sequence, or array.
1043 Parameters
1044 ----------
1045 obj : str or array_like
1046 Input data. If a string, variables in the current scope may be
1047 referenced by name.
1048 ldict : dict, optional
1049 A dictionary that replaces local operands in current frame.
1050 Ignored if `obj` is not a string or `gdict` is None.
1051 gdict : dict, optional
1052 A dictionary that replaces global operands in current frame.
1053 Ignored if `obj` is not a string.
1055 Returns
1056 -------
1057 out : matrix
1058 Returns a matrix object, which is a specialized 2-D array.
1060 See Also
1061 --------
1062 block :
1063 A generalization of this function for N-d arrays, that returns normal
1064 ndarrays.
1066 Examples
1067 --------
1068 >>> A = np.asmatrix('1 1; 1 1')
1069 >>> B = np.asmatrix('2 2; 2 2')
1070 >>> C = np.asmatrix('3 4; 5 6')
1071 >>> D = np.asmatrix('7 8; 9 0')
1073 All the following expressions construct the same block matrix:
1075 >>> np.bmat([[A, B], [C, D]])
1076 matrix([[1, 1, 2, 2],
1077 [1, 1, 2, 2],
1078 [3, 4, 7, 8],
1079 [5, 6, 9, 0]])
1080 >>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])
1081 matrix([[1, 1, 2, 2],
1082 [1, 1, 2, 2],
1083 [3, 4, 7, 8],
1084 [5, 6, 9, 0]])
1085 >>> np.bmat('A,B; C,D')
1086 matrix([[1, 1, 2, 2],
1087 [1, 1, 2, 2],
1088 [3, 4, 7, 8],
1089 [5, 6, 9, 0]])
1091 """
1092 if isinstance(obj, str):
1093 if gdict is None:
1094 # get previous frame
1095 frame = sys._getframe().f_back
1096 glob_dict = frame.f_globals
1097 loc_dict = frame.f_locals
1098 else:
1099 glob_dict = gdict
1100 loc_dict = ldict
1102 return matrix(_from_string(obj, glob_dict, loc_dict))
1104 if isinstance(obj, (tuple, list)):
1105 # [[A,B],[C,D]]
1106 arr_rows = []
1107 for row in obj:
1108 if isinstance(row, N.ndarray): # not 2-d
1109 return matrix(concatenate(obj, axis=-1))
1110 else:
1111 arr_rows.append(concatenate(row, axis=-1))
1112 return matrix(concatenate(arr_rows, axis=0))
1113 if isinstance(obj, N.ndarray):
1114 return matrix(obj)