matlib.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. from __future__ import division, absolute_import, print_function
  2. import numpy as np
  3. from numpy.matrixlib.defmatrix import matrix, asmatrix
  4. # need * as we're copying the numpy namespace
  5. from numpy import *
  6. __version__ = np.__version__
  7. __all__ = np.__all__[:] # copy numpy namespace
  8. __all__ += ['rand', 'randn', 'repmat']
  9. def empty(shape, dtype=None, order='C'):
  10. """Return a new matrix of given shape and type, without initializing entries.
  11. Parameters
  12. ----------
  13. shape : int or tuple of int
  14. Shape of the empty matrix.
  15. dtype : data-type, optional
  16. Desired output data-type.
  17. order : {'C', 'F'}, optional
  18. Whether to store multi-dimensional data in row-major
  19. (C-style) or column-major (Fortran-style) order in
  20. memory.
  21. See Also
  22. --------
  23. empty_like, zeros
  24. Notes
  25. -----
  26. `empty`, unlike `zeros`, does not set the matrix values to zero,
  27. and may therefore be marginally faster. On the other hand, it requires
  28. the user to manually set all the values in the array, and should be
  29. used with caution.
  30. Examples
  31. --------
  32. >>> import numpy.matlib
  33. >>> np.matlib.empty((2, 2)) # filled with random data
  34. matrix([[ 6.76425276e-320, 9.79033856e-307],
  35. [ 7.39337286e-309, 3.22135945e-309]]) #random
  36. >>> np.matlib.empty((2, 2), dtype=int)
  37. matrix([[ 6600475, 0],
  38. [ 6586976, 22740995]]) #random
  39. """
  40. return ndarray.__new__(matrix, shape, dtype, order=order)
  41. def ones(shape, dtype=None, order='C'):
  42. """
  43. Matrix of ones.
  44. Return a matrix of given shape and type, filled with ones.
  45. Parameters
  46. ----------
  47. shape : {sequence of ints, int}
  48. Shape of the matrix
  49. dtype : data-type, optional
  50. The desired data-type for the matrix, default is np.float64.
  51. order : {'C', 'F'}, optional
  52. Whether to store matrix in C- or Fortran-contiguous order,
  53. default is 'C'.
  54. Returns
  55. -------
  56. out : matrix
  57. Matrix of ones of given shape, dtype, and order.
  58. See Also
  59. --------
  60. ones : Array of ones.
  61. matlib.zeros : Zero matrix.
  62. Notes
  63. -----
  64. If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``,
  65. `out` becomes a single row matrix of shape ``(1,N)``.
  66. Examples
  67. --------
  68. >>> np.matlib.ones((2,3))
  69. matrix([[ 1., 1., 1.],
  70. [ 1., 1., 1.]])
  71. >>> np.matlib.ones(2)
  72. matrix([[ 1., 1.]])
  73. """
  74. a = ndarray.__new__(matrix, shape, dtype, order=order)
  75. a.fill(1)
  76. return a
  77. def zeros(shape, dtype=None, order='C'):
  78. """
  79. Return a matrix of given shape and type, filled with zeros.
  80. Parameters
  81. ----------
  82. shape : int or sequence of ints
  83. Shape of the matrix
  84. dtype : data-type, optional
  85. The desired data-type for the matrix, default is float.
  86. order : {'C', 'F'}, optional
  87. Whether to store the result in C- or Fortran-contiguous order,
  88. default is 'C'.
  89. Returns
  90. -------
  91. out : matrix
  92. Zero matrix of given shape, dtype, and order.
  93. See Also
  94. --------
  95. numpy.zeros : Equivalent array function.
  96. matlib.ones : Return a matrix of ones.
  97. Notes
  98. -----
  99. If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``,
  100. `out` becomes a single row matrix of shape ``(1,N)``.
  101. Examples
  102. --------
  103. >>> import numpy.matlib
  104. >>> np.matlib.zeros((2, 3))
  105. matrix([[ 0., 0., 0.],
  106. [ 0., 0., 0.]])
  107. >>> np.matlib.zeros(2)
  108. matrix([[ 0., 0.]])
  109. """
  110. a = ndarray.__new__(matrix, shape, dtype, order=order)
  111. a.fill(0)
  112. return a
  113. def identity(n,dtype=None):
  114. """
  115. Returns the square identity matrix of given size.
  116. Parameters
  117. ----------
  118. n : int
  119. Size of the returned identity matrix.
  120. dtype : data-type, optional
  121. Data-type of the output. Defaults to ``float``.
  122. Returns
  123. -------
  124. out : matrix
  125. `n` x `n` matrix with its main diagonal set to one,
  126. and all other elements zero.
  127. See Also
  128. --------
  129. numpy.identity : Equivalent array function.
  130. matlib.eye : More general matrix identity function.
  131. Examples
  132. --------
  133. >>> import numpy.matlib
  134. >>> np.matlib.identity(3, dtype=int)
  135. matrix([[1, 0, 0],
  136. [0, 1, 0],
  137. [0, 0, 1]])
  138. """
  139. a = array([1]+n*[0], dtype=dtype)
  140. b = empty((n, n), dtype=dtype)
  141. b.flat = a
  142. return b
  143. def eye(n,M=None, k=0, dtype=float, order='C'):
  144. """
  145. Return a matrix with ones on the diagonal and zeros elsewhere.
  146. Parameters
  147. ----------
  148. n : int
  149. Number of rows in the output.
  150. M : int, optional
  151. Number of columns in the output, defaults to `n`.
  152. k : int, optional
  153. Index of the diagonal: 0 refers to the main diagonal,
  154. a positive value refers to an upper diagonal,
  155. and a negative value to a lower diagonal.
  156. dtype : dtype, optional
  157. Data-type of the returned matrix.
  158. order : {'C', 'F'}, optional
  159. Whether the output should be stored in row-major (C-style) or
  160. column-major (Fortran-style) order in memory.
  161. .. versionadded:: 1.14.0
  162. Returns
  163. -------
  164. I : matrix
  165. A `n` x `M` matrix where all elements are equal to zero,
  166. except for the `k`-th diagonal, whose values are equal to one.
  167. See Also
  168. --------
  169. numpy.eye : Equivalent array function.
  170. identity : Square identity matrix.
  171. Examples
  172. --------
  173. >>> import numpy.matlib
  174. >>> np.matlib.eye(3, k=1, dtype=float)
  175. matrix([[ 0., 1., 0.],
  176. [ 0., 0., 1.],
  177. [ 0., 0., 0.]])
  178. """
  179. return asmatrix(np.eye(n, M=M, k=k, dtype=dtype, order=order))
  180. def rand(*args):
  181. """
  182. Return a matrix of random values with given shape.
  183. Create a matrix of the given shape and propagate it with
  184. random samples from a uniform distribution over ``[0, 1)``.
  185. Parameters
  186. ----------
  187. \\*args : Arguments
  188. Shape of the output.
  189. If given as N integers, each integer specifies the size of one
  190. dimension.
  191. If given as a tuple, this tuple gives the complete shape.
  192. Returns
  193. -------
  194. out : ndarray
  195. The matrix of random values with shape given by `\\*args`.
  196. See Also
  197. --------
  198. randn, numpy.random.rand
  199. Examples
  200. --------
  201. >>> import numpy.matlib
  202. >>> np.matlib.rand(2, 3)
  203. matrix([[ 0.68340382, 0.67926887, 0.83271405],
  204. [ 0.00793551, 0.20468222, 0.95253525]]) #random
  205. >>> np.matlib.rand((2, 3))
  206. matrix([[ 0.84682055, 0.73626594, 0.11308016],
  207. [ 0.85429008, 0.3294825 , 0.89139555]]) #random
  208. If the first argument is a tuple, other arguments are ignored:
  209. >>> np.matlib.rand((2, 3), 4)
  210. matrix([[ 0.46898646, 0.15163588, 0.95188261],
  211. [ 0.59208621, 0.09561818, 0.00583606]]) #random
  212. """
  213. if isinstance(args[0], tuple):
  214. args = args[0]
  215. return asmatrix(np.random.rand(*args))
  216. def randn(*args):
  217. """
  218. Return a random matrix with data from the "standard normal" distribution.
  219. `randn` generates a matrix filled with random floats sampled from a
  220. univariate "normal" (Gaussian) distribution of mean 0 and variance 1.
  221. Parameters
  222. ----------
  223. \\*args : Arguments
  224. Shape of the output.
  225. If given as N integers, each integer specifies the size of one
  226. dimension. If given as a tuple, this tuple gives the complete shape.
  227. Returns
  228. -------
  229. Z : matrix of floats
  230. A matrix of floating-point samples drawn from the standard normal
  231. distribution.
  232. See Also
  233. --------
  234. rand, random.randn
  235. Notes
  236. -----
  237. For random samples from :math:`N(\\mu, \\sigma^2)`, use:
  238. ``sigma * np.matlib.randn(...) + mu``
  239. Examples
  240. --------
  241. >>> import numpy.matlib
  242. >>> np.matlib.randn(1)
  243. matrix([[-0.09542833]]) #random
  244. >>> np.matlib.randn(1, 2, 3)
  245. matrix([[ 0.16198284, 0.0194571 , 0.18312985],
  246. [-0.7509172 , 1.61055 , 0.45298599]]) #random
  247. Two-by-four matrix of samples from :math:`N(3, 6.25)`:
  248. >>> 2.5 * np.matlib.randn((2, 4)) + 3
  249. matrix([[ 4.74085004, 8.89381862, 4.09042411, 4.83721922],
  250. [ 7.52373709, 5.07933944, -2.64043543, 0.45610557]]) #random
  251. """
  252. if isinstance(args[0], tuple):
  253. args = args[0]
  254. return asmatrix(np.random.randn(*args))
  255. def repmat(a, m, n):
  256. """
  257. Repeat a 0-D to 2-D array or matrix MxN times.
  258. Parameters
  259. ----------
  260. a : array_like
  261. The array or matrix to be repeated.
  262. m, n : int
  263. The number of times `a` is repeated along the first and second axes.
  264. Returns
  265. -------
  266. out : ndarray
  267. The result of repeating `a`.
  268. Examples
  269. --------
  270. >>> import numpy.matlib
  271. >>> a0 = np.array(1)
  272. >>> np.matlib.repmat(a0, 2, 3)
  273. array([[1, 1, 1],
  274. [1, 1, 1]])
  275. >>> a1 = np.arange(4)
  276. >>> np.matlib.repmat(a1, 2, 2)
  277. array([[0, 1, 2, 3, 0, 1, 2, 3],
  278. [0, 1, 2, 3, 0, 1, 2, 3]])
  279. >>> a2 = np.asmatrix(np.arange(6).reshape(2, 3))
  280. >>> np.matlib.repmat(a2, 2, 3)
  281. matrix([[0, 1, 2, 0, 1, 2, 0, 1, 2],
  282. [3, 4, 5, 3, 4, 5, 3, 4, 5],
  283. [0, 1, 2, 0, 1, 2, 0, 1, 2],
  284. [3, 4, 5, 3, 4, 5, 3, 4, 5]])
  285. """
  286. a = asanyarray(a)
  287. ndim = a.ndim
  288. if ndim == 0:
  289. origrows, origcols = (1, 1)
  290. elif ndim == 1:
  291. origrows, origcols = (1, a.shape[0])
  292. else:
  293. origrows, origcols = a.shape
  294. rows = origrows * m
  295. cols = origcols * n
  296. c = a.reshape(1, a.size).repeat(m, 0).reshape(rows, origcols).repeat(n, 0)
  297. return c.reshape(rows, cols)