defmatrix.py 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. __all__ = ['matrix', 'bmat', '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. 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, keepdims=True)._collapse(axis)
  402. def var(self, axis=None, dtype=None, out=None, ddof=0):
  403. """
  404. Returns the variance of the matrix elements, along the given axis.
  405. Refer to `numpy.var` for full documentation.
  406. See Also
  407. --------
  408. numpy.var
  409. Notes
  410. -----
  411. This is the same as `ndarray.var`, except that where an `ndarray` would
  412. be returned, a `matrix` object is returned instead.
  413. Examples
  414. --------
  415. >>> x = np.matrix(np.arange(12).reshape((3, 4)))
  416. >>> x
  417. matrix([[ 0, 1, 2, 3],
  418. [ 4, 5, 6, 7],
  419. [ 8, 9, 10, 11]])
  420. >>> x.var()
  421. 11.916666666666666
  422. >>> x.var(0)
  423. matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) # may vary
  424. >>> x.var(1)
  425. matrix([[1.25],
  426. [1.25],
  427. [1.25]])
  428. """
  429. return N.ndarray.var(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis)
  430. def prod(self, axis=None, dtype=None, out=None):
  431. """
  432. Return the product of the array elements over the given axis.
  433. Refer to `prod` for full documentation.
  434. See Also
  435. --------
  436. prod, ndarray.prod
  437. Notes
  438. -----
  439. Same as `ndarray.prod`, except, where that returns an `ndarray`, this
  440. returns a `matrix` object instead.
  441. Examples
  442. --------
  443. >>> x = np.matrix(np.arange(12).reshape((3,4))); x
  444. matrix([[ 0, 1, 2, 3],
  445. [ 4, 5, 6, 7],
  446. [ 8, 9, 10, 11]])
  447. >>> x.prod()
  448. 0
  449. >>> x.prod(0)
  450. matrix([[ 0, 45, 120, 231]])
  451. >>> x.prod(1)
  452. matrix([[ 0],
  453. [ 840],
  454. [7920]])
  455. """
  456. return N.ndarray.prod(self, axis, dtype, out, keepdims=True)._collapse(axis)
  457. def any(self, axis=None, out=None):
  458. """
  459. Test whether any array element along a given axis evaluates to True.
  460. Refer to `numpy.any` for full documentation.
  461. Parameters
  462. ----------
  463. axis : int, optional
  464. Axis along which logical OR is performed
  465. out : ndarray, optional
  466. Output to existing array instead of creating new one, must have
  467. same shape as expected output
  468. Returns
  469. -------
  470. any : bool, ndarray
  471. Returns a single bool if `axis` is ``None``; otherwise,
  472. returns `ndarray`
  473. """
  474. return N.ndarray.any(self, axis, out, keepdims=True)._collapse(axis)
  475. def all(self, axis=None, out=None):
  476. """
  477. Test whether all matrix elements along a given axis evaluate to True.
  478. Parameters
  479. ----------
  480. See `numpy.all` for complete descriptions
  481. See Also
  482. --------
  483. numpy.all
  484. Notes
  485. -----
  486. This is the same as `ndarray.all`, but it returns a `matrix` object.
  487. Examples
  488. --------
  489. >>> x = np.matrix(np.arange(12).reshape((3,4))); x
  490. matrix([[ 0, 1, 2, 3],
  491. [ 4, 5, 6, 7],
  492. [ 8, 9, 10, 11]])
  493. >>> y = x[0]; y
  494. matrix([[0, 1, 2, 3]])
  495. >>> (x == y)
  496. matrix([[ True, True, True, True],
  497. [False, False, False, False],
  498. [False, False, False, False]])
  499. >>> (x == y).all()
  500. False
  501. >>> (x == y).all(0)
  502. matrix([[False, False, False, False]])
  503. >>> (x == y).all(1)
  504. matrix([[ True],
  505. [False],
  506. [False]])
  507. """
  508. return N.ndarray.all(self, axis, out, keepdims=True)._collapse(axis)
  509. def max(self, axis=None, out=None):
  510. """
  511. Return the maximum value along an axis.
  512. Parameters
  513. ----------
  514. See `amax` for complete descriptions
  515. See Also
  516. --------
  517. amax, ndarray.max
  518. Notes
  519. -----
  520. This is the same as `ndarray.max`, but returns a `matrix` object
  521. where `ndarray.max` would return an ndarray.
  522. Examples
  523. --------
  524. >>> x = np.matrix(np.arange(12).reshape((3,4))); x
  525. matrix([[ 0, 1, 2, 3],
  526. [ 4, 5, 6, 7],
  527. [ 8, 9, 10, 11]])
  528. >>> x.max()
  529. 11
  530. >>> x.max(0)
  531. matrix([[ 8, 9, 10, 11]])
  532. >>> x.max(1)
  533. matrix([[ 3],
  534. [ 7],
  535. [11]])
  536. """
  537. return N.ndarray.max(self, axis, out, keepdims=True)._collapse(axis)
  538. def argmax(self, axis=None, out=None):
  539. """
  540. Indexes of the maximum values along an axis.
  541. Return the indexes of the first occurrences of the maximum values
  542. along the specified axis. If axis is None, the index is for the
  543. flattened matrix.
  544. Parameters
  545. ----------
  546. See `numpy.argmax` for complete descriptions
  547. See Also
  548. --------
  549. numpy.argmax
  550. Notes
  551. -----
  552. This is the same as `ndarray.argmax`, but returns a `matrix` object
  553. where `ndarray.argmax` would return an `ndarray`.
  554. Examples
  555. --------
  556. >>> x = np.matrix(np.arange(12).reshape((3,4))); x
  557. matrix([[ 0, 1, 2, 3],
  558. [ 4, 5, 6, 7],
  559. [ 8, 9, 10, 11]])
  560. >>> x.argmax()
  561. 11
  562. >>> x.argmax(0)
  563. matrix([[2, 2, 2, 2]])
  564. >>> x.argmax(1)
  565. matrix([[3],
  566. [3],
  567. [3]])
  568. """
  569. return N.ndarray.argmax(self, axis, out)._align(axis)
  570. def min(self, axis=None, out=None):
  571. """
  572. Return the minimum value along an axis.
  573. Parameters
  574. ----------
  575. See `amin` for complete descriptions.
  576. See Also
  577. --------
  578. amin, ndarray.min
  579. Notes
  580. -----
  581. This is the same as `ndarray.min`, but returns a `matrix` object
  582. where `ndarray.min` would return an ndarray.
  583. Examples
  584. --------
  585. >>> x = -np.matrix(np.arange(12).reshape((3,4))); x
  586. matrix([[ 0, -1, -2, -3],
  587. [ -4, -5, -6, -7],
  588. [ -8, -9, -10, -11]])
  589. >>> x.min()
  590. -11
  591. >>> x.min(0)
  592. matrix([[ -8, -9, -10, -11]])
  593. >>> x.min(1)
  594. matrix([[ -3],
  595. [ -7],
  596. [-11]])
  597. """
  598. return N.ndarray.min(self, axis, out, keepdims=True)._collapse(axis)
  599. def argmin(self, axis=None, out=None):
  600. """
  601. Indexes of the minimum values along an axis.
  602. Return the indexes of the first occurrences of the minimum values
  603. along the specified axis. If axis is None, the index is for the
  604. flattened matrix.
  605. Parameters
  606. ----------
  607. See `numpy.argmin` for complete descriptions.
  608. See Also
  609. --------
  610. numpy.argmin
  611. Notes
  612. -----
  613. This is the same as `ndarray.argmin`, but returns a `matrix` object
  614. where `ndarray.argmin` would return an `ndarray`.
  615. Examples
  616. --------
  617. >>> x = -np.matrix(np.arange(12).reshape((3,4))); x
  618. matrix([[ 0, -1, -2, -3],
  619. [ -4, -5, -6, -7],
  620. [ -8, -9, -10, -11]])
  621. >>> x.argmin()
  622. 11
  623. >>> x.argmin(0)
  624. matrix([[2, 2, 2, 2]])
  625. >>> x.argmin(1)
  626. matrix([[3],
  627. [3],
  628. [3]])
  629. """
  630. return N.ndarray.argmin(self, axis, out)._align(axis)
  631. def ptp(self, axis=None, out=None):
  632. """
  633. Peak-to-peak (maximum - minimum) value along the given axis.
  634. Refer to `numpy.ptp` for full documentation.
  635. See Also
  636. --------
  637. numpy.ptp
  638. Notes
  639. -----
  640. Same as `ndarray.ptp`, except, where that would return an `ndarray` object,
  641. this returns a `matrix` object.
  642. Examples
  643. --------
  644. >>> x = np.matrix(np.arange(12).reshape((3,4))); x
  645. matrix([[ 0, 1, 2, 3],
  646. [ 4, 5, 6, 7],
  647. [ 8, 9, 10, 11]])
  648. >>> x.ptp()
  649. 11
  650. >>> x.ptp(0)
  651. matrix([[8, 8, 8, 8]])
  652. >>> x.ptp(1)
  653. matrix([[3],
  654. [3],
  655. [3]])
  656. """
  657. return N.ptp(self, axis, out)._align(axis)
  658. @property
  659. def I(self):
  660. """
  661. Returns the (multiplicative) inverse of invertible `self`.
  662. Parameters
  663. ----------
  664. None
  665. Returns
  666. -------
  667. ret : matrix object
  668. If `self` is non-singular, `ret` is such that ``ret * self`` ==
  669. ``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return
  670. ``True``.
  671. Raises
  672. ------
  673. numpy.linalg.LinAlgError: Singular matrix
  674. If `self` is singular.
  675. See Also
  676. --------
  677. linalg.inv
  678. Examples
  679. --------
  680. >>> m = np.matrix('[1, 2; 3, 4]'); m
  681. matrix([[1, 2],
  682. [3, 4]])
  683. >>> m.getI()
  684. matrix([[-2. , 1. ],
  685. [ 1.5, -0.5]])
  686. >>> m.getI() * m
  687. matrix([[ 1., 0.], # may vary
  688. [ 0., 1.]])
  689. """
  690. M, N = self.shape
  691. if M == N:
  692. from numpy.linalg import inv as func
  693. else:
  694. from numpy.linalg import pinv as func
  695. return asmatrix(func(self))
  696. @property
  697. def A(self):
  698. """
  699. Return `self` as an `ndarray` object.
  700. Equivalent to ``np.asarray(self)``.
  701. Parameters
  702. ----------
  703. None
  704. Returns
  705. -------
  706. ret : ndarray
  707. `self` as an `ndarray`
  708. Examples
  709. --------
  710. >>> x = np.matrix(np.arange(12).reshape((3,4))); x
  711. matrix([[ 0, 1, 2, 3],
  712. [ 4, 5, 6, 7],
  713. [ 8, 9, 10, 11]])
  714. >>> x.getA()
  715. array([[ 0, 1, 2, 3],
  716. [ 4, 5, 6, 7],
  717. [ 8, 9, 10, 11]])
  718. """
  719. return self.__array__()
  720. @property
  721. def A1(self):
  722. """
  723. Return `self` as a flattened `ndarray`.
  724. Equivalent to ``np.asarray(x).ravel()``
  725. Parameters
  726. ----------
  727. None
  728. Returns
  729. -------
  730. ret : ndarray
  731. `self`, 1-D, as an `ndarray`
  732. Examples
  733. --------
  734. >>> x = np.matrix(np.arange(12).reshape((3,4))); x
  735. matrix([[ 0, 1, 2, 3],
  736. [ 4, 5, 6, 7],
  737. [ 8, 9, 10, 11]])
  738. >>> x.getA1()
  739. array([ 0, 1, 2, ..., 9, 10, 11])
  740. """
  741. return self.__array__().ravel()
  742. def ravel(self, order='C'):
  743. """
  744. Return a flattened matrix.
  745. Refer to `numpy.ravel` for more documentation.
  746. Parameters
  747. ----------
  748. order : {'C', 'F', 'A', 'K'}, optional
  749. The elements of `m` are read using this index order. 'C' means to
  750. index the elements in C-like order, with the last axis index
  751. changing fastest, back to the first axis index changing slowest.
  752. 'F' means to index the elements in Fortran-like index order, with
  753. the first index changing fastest, and the last index changing
  754. slowest. Note that the 'C' and 'F' options take no account of the
  755. memory layout of the underlying array, and only refer to the order
  756. of axis indexing. 'A' means to read the elements in Fortran-like
  757. index order if `m` is Fortran *contiguous* in memory, C-like order
  758. otherwise. 'K' means to read the elements in the order they occur
  759. in memory, except for reversing the data when strides are negative.
  760. By default, 'C' index order is used.
  761. Returns
  762. -------
  763. ret : matrix
  764. Return the matrix flattened to shape `(1, N)` where `N`
  765. is the number of elements in the original matrix.
  766. A copy is made only if necessary.
  767. See Also
  768. --------
  769. matrix.flatten : returns a similar output matrix but always a copy
  770. matrix.flat : a flat iterator on the array.
  771. numpy.ravel : related function which returns an ndarray
  772. """
  773. return N.ndarray.ravel(self, order=order)
  774. @property
  775. def T(self):
  776. """
  777. Returns the transpose of the matrix.
  778. Does *not* conjugate! For the complex conjugate transpose, use ``.H``.
  779. Parameters
  780. ----------
  781. None
  782. Returns
  783. -------
  784. ret : matrix object
  785. The (non-conjugated) transpose of the matrix.
  786. See Also
  787. --------
  788. transpose, getH
  789. Examples
  790. --------
  791. >>> m = np.matrix('[1, 2; 3, 4]')
  792. >>> m
  793. matrix([[1, 2],
  794. [3, 4]])
  795. >>> m.getT()
  796. matrix([[1, 3],
  797. [2, 4]])
  798. """
  799. return self.transpose()
  800. @property
  801. def H(self):
  802. """
  803. Returns the (complex) conjugate transpose of `self`.
  804. Equivalent to ``np.transpose(self)`` if `self` is real-valued.
  805. Parameters
  806. ----------
  807. None
  808. Returns
  809. -------
  810. ret : matrix object
  811. complex conjugate transpose of `self`
  812. Examples
  813. --------
  814. >>> x = np.matrix(np.arange(12).reshape((3,4)))
  815. >>> z = x - 1j*x; z
  816. matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j],
  817. [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j],
  818. [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]])
  819. >>> z.getH()
  820. matrix([[ 0. -0.j, 4. +4.j, 8. +8.j],
  821. [ 1. +1.j, 5. +5.j, 9. +9.j],
  822. [ 2. +2.j, 6. +6.j, 10.+10.j],
  823. [ 3. +3.j, 7. +7.j, 11.+11.j]])
  824. """
  825. if issubclass(self.dtype.type, N.complexfloating):
  826. return self.transpose().conjugate()
  827. else:
  828. return self.transpose()
  829. # kept for compatibility
  830. getT = T.fget
  831. getA = A.fget
  832. getA1 = A1.fget
  833. getH = H.fget
  834. getI = I.fget
  835. def _from_string(str, gdict, ldict):
  836. rows = str.split(';')
  837. rowtup = []
  838. for row in rows:
  839. trow = row.split(',')
  840. newrow = []
  841. for x in trow:
  842. newrow.extend(x.split())
  843. trow = newrow
  844. coltup = []
  845. for col in trow:
  846. col = col.strip()
  847. try:
  848. thismat = ldict[col]
  849. except KeyError:
  850. try:
  851. thismat = gdict[col]
  852. except KeyError as e:
  853. raise NameError(f"name {col!r} is not defined") from None
  854. coltup.append(thismat)
  855. rowtup.append(concatenate(coltup, axis=-1))
  856. return concatenate(rowtup, axis=0)
  857. @set_module('numpy')
  858. def bmat(obj, ldict=None, gdict=None):
  859. """
  860. Build a matrix object from a string, nested sequence, or array.
  861. Parameters
  862. ----------
  863. obj : str or array_like
  864. Input data. If a string, variables in the current scope may be
  865. referenced by name.
  866. ldict : dict, optional
  867. A dictionary that replaces local operands in current frame.
  868. Ignored if `obj` is not a string or `gdict` is None.
  869. gdict : dict, optional
  870. A dictionary that replaces global operands in current frame.
  871. Ignored if `obj` is not a string.
  872. Returns
  873. -------
  874. out : matrix
  875. Returns a matrix object, which is a specialized 2-D array.
  876. See Also
  877. --------
  878. block :
  879. A generalization of this function for N-d arrays, that returns normal
  880. ndarrays.
  881. Examples
  882. --------
  883. >>> import numpy as np
  884. >>> A = np.asmatrix('1 1; 1 1')
  885. >>> B = np.asmatrix('2 2; 2 2')
  886. >>> C = np.asmatrix('3 4; 5 6')
  887. >>> D = np.asmatrix('7 8; 9 0')
  888. All the following expressions construct the same block matrix:
  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. >>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])
  895. matrix([[1, 1, 2, 2],
  896. [1, 1, 2, 2],
  897. [3, 4, 7, 8],
  898. [5, 6, 9, 0]])
  899. >>> np.bmat('A,B; C,D')
  900. matrix([[1, 1, 2, 2],
  901. [1, 1, 2, 2],
  902. [3, 4, 7, 8],
  903. [5, 6, 9, 0]])
  904. """
  905. if isinstance(obj, str):
  906. if gdict is None:
  907. # get previous frame
  908. frame = sys._getframe().f_back
  909. glob_dict = frame.f_globals
  910. loc_dict = frame.f_locals
  911. else:
  912. glob_dict = gdict
  913. loc_dict = ldict
  914. return matrix(_from_string(obj, glob_dict, loc_dict))
  915. if isinstance(obj, (tuple, list)):
  916. # [[A,B],[C,D]]
  917. arr_rows = []
  918. for row in obj:
  919. if isinstance(row, N.ndarray): # not 2-d
  920. return matrix(concatenate(obj, axis=-1))
  921. else:
  922. arr_rows.append(concatenate(row, axis=-1))
  923. return matrix(concatenate(arr_rows, axis=0))
  924. if isinstance(obj, N.ndarray):
  925. return matrix(obj)