defmatrix.py 33 KB

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