defmatrix.py 30 KB

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