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