Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/numpy/matrixlib/defmatrix.py: 19%
238 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1__all__ = ['matrix', 'bmat', 'mat', 'asmatrix']
3import sys
4import warnings
5import ast
6import numpy.core.numeric as N
7from numpy.core.numeric import concatenate, isscalar
8from numpy.core.overrides import set_module
9# While not in __all__, matrix_power used to be defined here, so we import
10# it for backward compatibility.
11from numpy.linalg import matrix_power
14def _convert_from_string(data):
15 for char in '[]':
16 data = data.replace(char, '')
18 rows = data.split(';')
19 newdata = []
20 count = 0
21 for row in rows:
22 trow = row.split(',')
23 newrow = []
24 for col in trow:
25 temp = col.split()
26 newrow.extend(map(ast.literal_eval, temp))
27 if count == 0:
28 Ncols = len(newrow)
29 elif len(newrow) != Ncols:
30 raise ValueError("Rows not the same size.")
31 count += 1
32 newdata.append(newrow)
33 return newdata
36@set_module('numpy')
37def asmatrix(data, dtype=None):
38 """
39 Interpret the input as a matrix.
41 Unlike `matrix`, `asmatrix` does not make a copy if the input is already
42 a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``.
44 Parameters
45 ----------
46 data : array_like
47 Input data.
48 dtype : data-type
49 Data-type of the output matrix.
51 Returns
52 -------
53 mat : matrix
54 `data` interpreted as a matrix.
56 Examples
57 --------
58 >>> x = np.array([[1, 2], [3, 4]])
60 >>> m = np.asmatrix(x)
62 >>> x[0,0] = 5
64 >>> m
65 matrix([[5, 2],
66 [3, 4]])
68 """
69 return matrix(data, dtype=dtype, copy=False)
72@set_module('numpy')
73class matrix(N.ndarray):
74 """
75 matrix(data, dtype=None, copy=True)
77 .. note:: It is no longer recommended to use this class, even for linear
78 algebra. Instead use regular arrays. The class may be removed
79 in the future.
81 Returns a matrix from an array-like object, or from a string of data.
82 A matrix is a specialized 2-D array that retains its 2-D nature
83 through operations. It has certain special operators, such as ``*``
84 (matrix multiplication) and ``**`` (matrix power).
86 Parameters
87 ----------
88 data : array_like or string
89 If `data` is a string, it is interpreted as a matrix with commas
90 or spaces separating columns, and semicolons separating rows.
91 dtype : data-type
92 Data-type of the output matrix.
93 copy : bool
94 If `data` is already an `ndarray`, then this flag determines
95 whether the data is copied (the default), or whether a view is
96 constructed.
98 See Also
99 --------
100 array
102 Examples
103 --------
104 >>> a = np.matrix('1 2; 3 4')
105 >>> a
106 matrix([[1, 2],
107 [3, 4]])
109 >>> np.matrix([[1, 2], [3, 4]])
110 matrix([[1, 2],
111 [3, 4]])
113 """
114 __array_priority__ = 10.0
115 def __new__(subtype, data, dtype=None, copy=True):
116 warnings.warn('the matrix subclass is not the recommended way to '
117 'represent matrices or deal with linear algebra (see '
118 'https://docs.scipy.org/doc/numpy/user/'
119 'numpy-for-matlab-users.html). '
120 'Please adjust your code to use regular ndarray.',
121 PendingDeprecationWarning, stacklevel=2)
122 if isinstance(data, matrix):
123 dtype2 = data.dtype
124 if (dtype is None):
125 dtype = dtype2
126 if (dtype2 == dtype) and (not copy):
127 return data
128 return data.astype(dtype)
130 if isinstance(data, N.ndarray):
131 if dtype is None:
132 intype = data.dtype
133 else:
134 intype = N.dtype(dtype)
135 new = data.view(subtype)
136 if intype != data.dtype:
137 return new.astype(intype)
138 if copy: return new.copy()
139 else: return new
141 if isinstance(data, str):
142 data = _convert_from_string(data)
144 # now convert data to an array
145 arr = N.array(data, dtype=dtype, copy=copy)
146 ndim = arr.ndim
147 shape = arr.shape
148 if (ndim > 2):
149 raise ValueError("matrix must be 2-dimensional")
150 elif ndim == 0:
151 shape = (1, 1)
152 elif ndim == 1:
153 shape = (1, shape[0])
155 order = 'C'
156 if (ndim == 2) and arr.flags.fortran:
157 order = 'F'
159 if not (order or arr.flags.contiguous):
160 arr = arr.copy()
162 ret = N.ndarray.__new__(subtype, shape, arr.dtype,
163 buffer=arr,
164 order=order)
165 return ret
167 def __array_finalize__(self, obj):
168 self._getitem = False
169 if (isinstance(obj, matrix) and obj._getitem): return
170 ndim = self.ndim
171 if (ndim == 2):
172 return
173 if (ndim > 2):
174 newshape = tuple([x for x in self.shape if x > 1])
175 ndim = len(newshape)
176 if ndim == 2:
177 self.shape = newshape
178 return
179 elif (ndim > 2):
180 raise ValueError("shape too large to be a matrix.")
181 else:
182 newshape = self.shape
183 if ndim == 0:
184 self.shape = (1, 1)
185 elif ndim == 1:
186 self.shape = (1, newshape[0])
187 return
189 def __getitem__(self, index):
190 self._getitem = True
192 try:
193 out = N.ndarray.__getitem__(self, index)
194 finally:
195 self._getitem = False
197 if not isinstance(out, N.ndarray):
198 return out
200 if out.ndim == 0:
201 return out[()]
202 if out.ndim == 1:
203 sh = out.shape[0]
204 # Determine when we should have a column array
205 try:
206 n = len(index)
207 except Exception:
208 n = 0
209 if n > 1 and isscalar(index[1]):
210 out.shape = (sh, 1)
211 else:
212 out.shape = (1, sh)
213 return out
215 def __mul__(self, other):
216 if isinstance(other, (N.ndarray, list, tuple)) :
217 # This promotes 1-D vectors to row vectors
218 return N.dot(self, asmatrix(other))
219 if isscalar(other) or not hasattr(other, '__rmul__') :
220 return N.dot(self, other)
221 return NotImplemented
223 def __rmul__(self, other):
224 return N.dot(other, self)
226 def __imul__(self, other):
227 self[:] = self * other
228 return self
230 def __pow__(self, other):
231 return matrix_power(self, other)
233 def __ipow__(self, other):
234 self[:] = self ** other
235 return self
237 def __rpow__(self, other):
238 return NotImplemented
240 def _align(self, axis):
241 """A convenience function for operations that need to preserve axis
242 orientation.
243 """
244 if axis is None:
245 return self[0, 0]
246 elif axis==0:
247 return self
248 elif axis==1:
249 return self.transpose()
250 else:
251 raise ValueError("unsupported axis")
253 def _collapse(self, axis):
254 """A convenience function for operations that want to collapse
255 to a scalar like _align, but are using keepdims=True
256 """
257 if axis is None:
258 return self[0, 0]
259 else:
260 return self
262 # Necessary because base-class tolist expects dimension
263 # reduction by x[0]
264 def tolist(self):
265 """
266 Return the matrix as a (possibly nested) list.
268 See `ndarray.tolist` for full documentation.
270 See Also
271 --------
272 ndarray.tolist
274 Examples
275 --------
276 >>> x = np.matrix(np.arange(12).reshape((3,4))); x
277 matrix([[ 0, 1, 2, 3],
278 [ 4, 5, 6, 7],
279 [ 8, 9, 10, 11]])
280 >>> x.tolist()
281 [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
283 """
284 return self.__array__().tolist()
286 # To preserve orientation of result...
287 def sum(self, axis=None, dtype=None, out=None):
288 """
289 Returns the sum of the matrix elements, along the given axis.
291 Refer to `numpy.sum` for full documentation.
293 See Also
294 --------
295 numpy.sum
297 Notes
298 -----
299 This is the same as `ndarray.sum`, except that where an `ndarray` would
300 be returned, a `matrix` object is returned instead.
302 Examples
303 --------
304 >>> x = np.matrix([[1, 2], [4, 3]])
305 >>> x.sum()
306 10
307 >>> x.sum(axis=1)
308 matrix([[3],
309 [7]])
310 >>> x.sum(axis=1, dtype='float')
311 matrix([[3.],
312 [7.]])
313 >>> out = np.zeros((2, 1), dtype='float')
314 >>> x.sum(axis=1, dtype='float', out=np.asmatrix(out))
315 matrix([[3.],
316 [7.]])
318 """
319 return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis)
322 # To update docstring from array to matrix...
323 def squeeze(self, axis=None):
324 """
325 Return a possibly reshaped matrix.
327 Refer to `numpy.squeeze` for more documentation.
329 Parameters
330 ----------
331 axis : None or int or tuple of ints, optional
332 Selects a subset of the axes of length one in the shape.
333 If an axis is selected with shape entry greater than one,
334 an error is raised.
336 Returns
337 -------
338 squeezed : matrix
339 The matrix, but as a (1, N) matrix if it had shape (N, 1).
341 See Also
342 --------
343 numpy.squeeze : related function
345 Notes
346 -----
347 If `m` has a single column then that column is returned
348 as the single row of a matrix. Otherwise `m` is returned.
349 The returned matrix is always either `m` itself or a view into `m`.
350 Supplying an axis keyword argument will not affect the returned matrix
351 but it may cause an error to be raised.
353 Examples
354 --------
355 >>> c = np.matrix([[1], [2]])
356 >>> c
357 matrix([[1],
358 [2]])
359 >>> c.squeeze()
360 matrix([[1, 2]])
361 >>> r = c.T
362 >>> r
363 matrix([[1, 2]])
364 >>> r.squeeze()
365 matrix([[1, 2]])
366 >>> m = np.matrix([[1, 2], [3, 4]])
367 >>> m.squeeze()
368 matrix([[1, 2],
369 [3, 4]])
371 """
372 return N.ndarray.squeeze(self, axis=axis)
375 # To update docstring from array to matrix...
376 def flatten(self, order='C'):
377 """
378 Return a flattened copy of the matrix.
380 All `N` elements of the matrix are placed into a single row.
382 Parameters
383 ----------
384 order : {'C', 'F', 'A', 'K'}, optional
385 'C' means to flatten in row-major (C-style) order. 'F' means to
386 flatten in column-major (Fortran-style) order. 'A' means to
387 flatten in column-major order if `m` is Fortran *contiguous* in
388 memory, row-major order otherwise. 'K' means to flatten `m` in
389 the order the elements occur in memory. The default is 'C'.
391 Returns
392 -------
393 y : matrix
394 A copy of the matrix, flattened to a `(1, N)` matrix where `N`
395 is the number of elements in the original matrix.
397 See Also
398 --------
399 ravel : Return a flattened array.
400 flat : A 1-D flat iterator over the matrix.
402 Examples
403 --------
404 >>> m = np.matrix([[1,2], [3,4]])
405 >>> m.flatten()
406 matrix([[1, 2, 3, 4]])
407 >>> m.flatten('F')
408 matrix([[1, 3, 2, 4]])
410 """
411 return N.ndarray.flatten(self, order=order)
413 def mean(self, axis=None, dtype=None, out=None):
414 """
415 Returns the average of the matrix elements along the given axis.
417 Refer to `numpy.mean` for full documentation.
419 See Also
420 --------
421 numpy.mean
423 Notes
424 -----
425 Same as `ndarray.mean` except that, where that returns an `ndarray`,
426 this returns a `matrix` object.
428 Examples
429 --------
430 >>> x = np.matrix(np.arange(12).reshape((3, 4)))
431 >>> x
432 matrix([[ 0, 1, 2, 3],
433 [ 4, 5, 6, 7],
434 [ 8, 9, 10, 11]])
435 >>> x.mean()
436 5.5
437 >>> x.mean(0)
438 matrix([[4., 5., 6., 7.]])
439 >>> x.mean(1)
440 matrix([[ 1.5],
441 [ 5.5],
442 [ 9.5]])
444 """
445 return N.ndarray.mean(self, axis, dtype, out, keepdims=True)._collapse(axis)
447 def std(self, axis=None, dtype=None, out=None, ddof=0):
448 """
449 Return the standard deviation of the array elements along the given axis.
451 Refer to `numpy.std` for full documentation.
453 See Also
454 --------
455 numpy.std
457 Notes
458 -----
459 This is the same as `ndarray.std`, except that where an `ndarray` would
460 be returned, a `matrix` object is returned instead.
462 Examples
463 --------
464 >>> x = np.matrix(np.arange(12).reshape((3, 4)))
465 >>> x
466 matrix([[ 0, 1, 2, 3],
467 [ 4, 5, 6, 7],
468 [ 8, 9, 10, 11]])
469 >>> x.std()
470 3.4520525295346629 # may vary
471 >>> x.std(0)
472 matrix([[ 3.26598632, 3.26598632, 3.26598632, 3.26598632]]) # may vary
473 >>> x.std(1)
474 matrix([[ 1.11803399],
475 [ 1.11803399],
476 [ 1.11803399]])
478 """
479 return N.ndarray.std(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis)
481 def var(self, axis=None, dtype=None, out=None, ddof=0):
482 """
483 Returns the variance of the matrix elements, along the given axis.
485 Refer to `numpy.var` for full documentation.
487 See Also
488 --------
489 numpy.var
491 Notes
492 -----
493 This is the same as `ndarray.var`, except that where an `ndarray` would
494 be returned, a `matrix` object is returned instead.
496 Examples
497 --------
498 >>> x = np.matrix(np.arange(12).reshape((3, 4)))
499 >>> x
500 matrix([[ 0, 1, 2, 3],
501 [ 4, 5, 6, 7],
502 [ 8, 9, 10, 11]])
503 >>> x.var()
504 11.916666666666666
505 >>> x.var(0)
506 matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) # may vary
507 >>> x.var(1)
508 matrix([[1.25],
509 [1.25],
510 [1.25]])
512 """
513 return N.ndarray.var(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis)
515 def prod(self, axis=None, dtype=None, out=None):
516 """
517 Return the product of the array elements over the given axis.
519 Refer to `prod` for full documentation.
521 See Also
522 --------
523 prod, ndarray.prod
525 Notes
526 -----
527 Same as `ndarray.prod`, except, where that returns an `ndarray`, this
528 returns a `matrix` object instead.
530 Examples
531 --------
532 >>> x = np.matrix(np.arange(12).reshape((3,4))); x
533 matrix([[ 0, 1, 2, 3],
534 [ 4, 5, 6, 7],
535 [ 8, 9, 10, 11]])
536 >>> x.prod()
537 0
538 >>> x.prod(0)
539 matrix([[ 0, 45, 120, 231]])
540 >>> x.prod(1)
541 matrix([[ 0],
542 [ 840],
543 [7920]])
545 """
546 return N.ndarray.prod(self, axis, dtype, out, keepdims=True)._collapse(axis)
548 def any(self, axis=None, out=None):
549 """
550 Test whether any array element along a given axis evaluates to True.
552 Refer to `numpy.any` for full documentation.
554 Parameters
555 ----------
556 axis : int, optional
557 Axis along which logical OR is performed
558 out : ndarray, optional
559 Output to existing array instead of creating new one, must have
560 same shape as expected output
562 Returns
563 -------
564 any : bool, ndarray
565 Returns a single bool if `axis` is ``None``; otherwise,
566 returns `ndarray`
568 """
569 return N.ndarray.any(self, axis, out, keepdims=True)._collapse(axis)
571 def all(self, axis=None, out=None):
572 """
573 Test whether all matrix elements along a given axis evaluate to True.
575 Parameters
576 ----------
577 See `numpy.all` for complete descriptions
579 See Also
580 --------
581 numpy.all
583 Notes
584 -----
585 This is the same as `ndarray.all`, but it returns a `matrix` object.
587 Examples
588 --------
589 >>> x = np.matrix(np.arange(12).reshape((3,4))); x
590 matrix([[ 0, 1, 2, 3],
591 [ 4, 5, 6, 7],
592 [ 8, 9, 10, 11]])
593 >>> y = x[0]; y
594 matrix([[0, 1, 2, 3]])
595 >>> (x == y)
596 matrix([[ True, True, True, True],
597 [False, False, False, False],
598 [False, False, False, False]])
599 >>> (x == y).all()
600 False
601 >>> (x == y).all(0)
602 matrix([[False, False, False, False]])
603 >>> (x == y).all(1)
604 matrix([[ True],
605 [False],
606 [False]])
608 """
609 return N.ndarray.all(self, axis, out, keepdims=True)._collapse(axis)
611 def max(self, axis=None, out=None):
612 """
613 Return the maximum value along an axis.
615 Parameters
616 ----------
617 See `amax` for complete descriptions
619 See Also
620 --------
621 amax, ndarray.max
623 Notes
624 -----
625 This is the same as `ndarray.max`, but returns a `matrix` object
626 where `ndarray.max` would return an ndarray.
628 Examples
629 --------
630 >>> x = np.matrix(np.arange(12).reshape((3,4))); x
631 matrix([[ 0, 1, 2, 3],
632 [ 4, 5, 6, 7],
633 [ 8, 9, 10, 11]])
634 >>> x.max()
635 11
636 >>> x.max(0)
637 matrix([[ 8, 9, 10, 11]])
638 >>> x.max(1)
639 matrix([[ 3],
640 [ 7],
641 [11]])
643 """
644 return N.ndarray.max(self, axis, out, keepdims=True)._collapse(axis)
646 def argmax(self, axis=None, out=None):
647 """
648 Indexes of the maximum values along an axis.
650 Return the indexes of the first occurrences of the maximum values
651 along the specified axis. If axis is None, the index is for the
652 flattened matrix.
654 Parameters
655 ----------
656 See `numpy.argmax` for complete descriptions
658 See Also
659 --------
660 numpy.argmax
662 Notes
663 -----
664 This is the same as `ndarray.argmax`, but returns a `matrix` object
665 where `ndarray.argmax` would return an `ndarray`.
667 Examples
668 --------
669 >>> x = np.matrix(np.arange(12).reshape((3,4))); x
670 matrix([[ 0, 1, 2, 3],
671 [ 4, 5, 6, 7],
672 [ 8, 9, 10, 11]])
673 >>> x.argmax()
674 11
675 >>> x.argmax(0)
676 matrix([[2, 2, 2, 2]])
677 >>> x.argmax(1)
678 matrix([[3],
679 [3],
680 [3]])
682 """
683 return N.ndarray.argmax(self, axis, out)._align(axis)
685 def min(self, axis=None, out=None):
686 """
687 Return the minimum value along an axis.
689 Parameters
690 ----------
691 See `amin` for complete descriptions.
693 See Also
694 --------
695 amin, ndarray.min
697 Notes
698 -----
699 This is the same as `ndarray.min`, but returns a `matrix` object
700 where `ndarray.min` would return an ndarray.
702 Examples
703 --------
704 >>> x = -np.matrix(np.arange(12).reshape((3,4))); x
705 matrix([[ 0, -1, -2, -3],
706 [ -4, -5, -6, -7],
707 [ -8, -9, -10, -11]])
708 >>> x.min()
709 -11
710 >>> x.min(0)
711 matrix([[ -8, -9, -10, -11]])
712 >>> x.min(1)
713 matrix([[ -3],
714 [ -7],
715 [-11]])
717 """
718 return N.ndarray.min(self, axis, out, keepdims=True)._collapse(axis)
720 def argmin(self, axis=None, out=None):
721 """
722 Indexes of the minimum values along an axis.
724 Return the indexes of the first occurrences of the minimum values
725 along the specified axis. If axis is None, the index is for the
726 flattened matrix.
728 Parameters
729 ----------
730 See `numpy.argmin` for complete descriptions.
732 See Also
733 --------
734 numpy.argmin
736 Notes
737 -----
738 This is the same as `ndarray.argmin`, but returns a `matrix` object
739 where `ndarray.argmin` would return an `ndarray`.
741 Examples
742 --------
743 >>> x = -np.matrix(np.arange(12).reshape((3,4))); x
744 matrix([[ 0, -1, -2, -3],
745 [ -4, -5, -6, -7],
746 [ -8, -9, -10, -11]])
747 >>> x.argmin()
748 11
749 >>> x.argmin(0)
750 matrix([[2, 2, 2, 2]])
751 >>> x.argmin(1)
752 matrix([[3],
753 [3],
754 [3]])
756 """
757 return N.ndarray.argmin(self, axis, out)._align(axis)
759 def ptp(self, axis=None, out=None):
760 """
761 Peak-to-peak (maximum - minimum) value along the given axis.
763 Refer to `numpy.ptp` for full documentation.
765 See Also
766 --------
767 numpy.ptp
769 Notes
770 -----
771 Same as `ndarray.ptp`, except, where that would return an `ndarray` object,
772 this returns a `matrix` object.
774 Examples
775 --------
776 >>> x = np.matrix(np.arange(12).reshape((3,4))); x
777 matrix([[ 0, 1, 2, 3],
778 [ 4, 5, 6, 7],
779 [ 8, 9, 10, 11]])
780 >>> x.ptp()
781 11
782 >>> x.ptp(0)
783 matrix([[8, 8, 8, 8]])
784 >>> x.ptp(1)
785 matrix([[3],
786 [3],
787 [3]])
789 """
790 return N.ndarray.ptp(self, axis, out)._align(axis)
792 @property
793 def I(self):
794 """
795 Returns the (multiplicative) inverse of invertible `self`.
797 Parameters
798 ----------
799 None
801 Returns
802 -------
803 ret : matrix object
804 If `self` is non-singular, `ret` is such that ``ret * self`` ==
805 ``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return
806 ``True``.
808 Raises
809 ------
810 numpy.linalg.LinAlgError: Singular matrix
811 If `self` is singular.
813 See Also
814 --------
815 linalg.inv
817 Examples
818 --------
819 >>> m = np.matrix('[1, 2; 3, 4]'); m
820 matrix([[1, 2],
821 [3, 4]])
822 >>> m.getI()
823 matrix([[-2. , 1. ],
824 [ 1.5, -0.5]])
825 >>> m.getI() * m
826 matrix([[ 1., 0.], # may vary
827 [ 0., 1.]])
829 """
830 M, N = self.shape
831 if M == N:
832 from numpy.linalg import inv as func
833 else:
834 from numpy.linalg import pinv as func
835 return asmatrix(func(self))
837 @property
838 def A(self):
839 """
840 Return `self` as an `ndarray` object.
842 Equivalent to ``np.asarray(self)``.
844 Parameters
845 ----------
846 None
848 Returns
849 -------
850 ret : ndarray
851 `self` as an `ndarray`
853 Examples
854 --------
855 >>> x = np.matrix(np.arange(12).reshape((3,4))); x
856 matrix([[ 0, 1, 2, 3],
857 [ 4, 5, 6, 7],
858 [ 8, 9, 10, 11]])
859 >>> x.getA()
860 array([[ 0, 1, 2, 3],
861 [ 4, 5, 6, 7],
862 [ 8, 9, 10, 11]])
864 """
865 return self.__array__()
867 @property
868 def A1(self):
869 """
870 Return `self` as a flattened `ndarray`.
872 Equivalent to ``np.asarray(x).ravel()``
874 Parameters
875 ----------
876 None
878 Returns
879 -------
880 ret : ndarray
881 `self`, 1-D, as an `ndarray`
883 Examples
884 --------
885 >>> x = np.matrix(np.arange(12).reshape((3,4))); x
886 matrix([[ 0, 1, 2, 3],
887 [ 4, 5, 6, 7],
888 [ 8, 9, 10, 11]])
889 >>> x.getA1()
890 array([ 0, 1, 2, ..., 9, 10, 11])
893 """
894 return self.__array__().ravel()
897 def ravel(self, order='C'):
898 """
899 Return a flattened matrix.
901 Refer to `numpy.ravel` for more documentation.
903 Parameters
904 ----------
905 order : {'C', 'F', 'A', 'K'}, optional
906 The elements of `m` are read using this index order. 'C' means to
907 index the elements in C-like order, with the last axis index
908 changing fastest, back to the first axis index changing slowest.
909 'F' means to index the elements in Fortran-like index order, with
910 the first index changing fastest, and the last index changing
911 slowest. Note that the 'C' and 'F' options take no account of the
912 memory layout of the underlying array, and only refer to the order
913 of axis indexing. 'A' means to read the elements in Fortran-like
914 index order if `m` is Fortran *contiguous* in memory, C-like order
915 otherwise. 'K' means to read the elements in the order they occur
916 in memory, except for reversing the data when strides are negative.
917 By default, 'C' index order is used.
919 Returns
920 -------
921 ret : matrix
922 Return the matrix flattened to shape `(1, N)` where `N`
923 is the number of elements in the original matrix.
924 A copy is made only if necessary.
926 See Also
927 --------
928 matrix.flatten : returns a similar output matrix but always a copy
929 matrix.flat : a flat iterator on the array.
930 numpy.ravel : related function which returns an ndarray
932 """
933 return N.ndarray.ravel(self, order=order)
935 @property
936 def T(self):
937 """
938 Returns the transpose of the matrix.
940 Does *not* conjugate! For the complex conjugate transpose, use ``.H``.
942 Parameters
943 ----------
944 None
946 Returns
947 -------
948 ret : matrix object
949 The (non-conjugated) transpose of the matrix.
951 See Also
952 --------
953 transpose, getH
955 Examples
956 --------
957 >>> m = np.matrix('[1, 2; 3, 4]')
958 >>> m
959 matrix([[1, 2],
960 [3, 4]])
961 >>> m.getT()
962 matrix([[1, 3],
963 [2, 4]])
965 """
966 return self.transpose()
968 @property
969 def H(self):
970 """
971 Returns the (complex) conjugate transpose of `self`.
973 Equivalent to ``np.transpose(self)`` if `self` is real-valued.
975 Parameters
976 ----------
977 None
979 Returns
980 -------
981 ret : matrix object
982 complex conjugate transpose of `self`
984 Examples
985 --------
986 >>> x = np.matrix(np.arange(12).reshape((3,4)))
987 >>> z = x - 1j*x; z
988 matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j],
989 [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j],
990 [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]])
991 >>> z.getH()
992 matrix([[ 0. -0.j, 4. +4.j, 8. +8.j],
993 [ 1. +1.j, 5. +5.j, 9. +9.j],
994 [ 2. +2.j, 6. +6.j, 10.+10.j],
995 [ 3. +3.j, 7. +7.j, 11.+11.j]])
997 """
998 if issubclass(self.dtype.type, N.complexfloating):
999 return self.transpose().conjugate()
1000 else:
1001 return self.transpose()
1003 # kept for compatibility
1004 getT = T.fget
1005 getA = A.fget
1006 getA1 = A1.fget
1007 getH = H.fget
1008 getI = I.fget
1010def _from_string(str, gdict, ldict):
1011 rows = str.split(';')
1012 rowtup = []
1013 for row in rows:
1014 trow = row.split(',')
1015 newrow = []
1016 for x in trow:
1017 newrow.extend(x.split())
1018 trow = newrow
1019 coltup = []
1020 for col in trow:
1021 col = col.strip()
1022 try:
1023 thismat = ldict[col]
1024 except KeyError:
1025 try:
1026 thismat = gdict[col]
1027 except KeyError as e:
1028 raise NameError(f"name {col!r} is not defined") from None
1030 coltup.append(thismat)
1031 rowtup.append(concatenate(coltup, axis=-1))
1032 return concatenate(rowtup, axis=0)
1035@set_module('numpy')
1036def bmat(obj, ldict=None, gdict=None):
1037 """
1038 Build a matrix object from a string, nested sequence, or array.
1040 Parameters
1041 ----------
1042 obj : str or array_like
1043 Input data. If a string, variables in the current scope may be
1044 referenced by name.
1045 ldict : dict, optional
1046 A dictionary that replaces local operands in current frame.
1047 Ignored if `obj` is not a string or `gdict` is None.
1048 gdict : dict, optional
1049 A dictionary that replaces global operands in current frame.
1050 Ignored if `obj` is not a string.
1052 Returns
1053 -------
1054 out : matrix
1055 Returns a matrix object, which is a specialized 2-D array.
1057 See Also
1058 --------
1059 block :
1060 A generalization of this function for N-d arrays, that returns normal
1061 ndarrays.
1063 Examples
1064 --------
1065 >>> A = np.mat('1 1; 1 1')
1066 >>> B = np.mat('2 2; 2 2')
1067 >>> C = np.mat('3 4; 5 6')
1068 >>> D = np.mat('7 8; 9 0')
1070 All the following expressions construct the same block matrix:
1072 >>> np.bmat([[A, B], [C, D]])
1073 matrix([[1, 1, 2, 2],
1074 [1, 1, 2, 2],
1075 [3, 4, 7, 8],
1076 [5, 6, 9, 0]])
1077 >>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])
1078 matrix([[1, 1, 2, 2],
1079 [1, 1, 2, 2],
1080 [3, 4, 7, 8],
1081 [5, 6, 9, 0]])
1082 >>> np.bmat('A,B; C,D')
1083 matrix([[1, 1, 2, 2],
1084 [1, 1, 2, 2],
1085 [3, 4, 7, 8],
1086 [5, 6, 9, 0]])
1088 """
1089 if isinstance(obj, str):
1090 if gdict is None:
1091 # get previous frame
1092 frame = sys._getframe().f_back
1093 glob_dict = frame.f_globals
1094 loc_dict = frame.f_locals
1095 else:
1096 glob_dict = gdict
1097 loc_dict = ldict
1099 return matrix(_from_string(obj, glob_dict, loc_dict))
1101 if isinstance(obj, (tuple, list)):
1102 # [[A,B],[C,D]]
1103 arr_rows = []
1104 for row in obj:
1105 if isinstance(row, N.ndarray): # not 2-d
1106 return matrix(concatenate(obj, axis=-1))
1107 else:
1108 arr_rows.append(concatenate(row, axis=-1))
1109 return matrix(concatenate(arr_rows, axis=0))
1110 if isinstance(obj, N.ndarray):
1111 return matrix(obj)
1113mat = asmatrix