defmatrix.py 30 KB

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