defmatrix.py 30 KB

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