matlib.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import warnings
  2. # 2018-05-29, PendingDeprecationWarning added to matrix.__new__
  3. # 2020-01-23, numpy 1.19.0 PendingDeprecatonWarning
  4. warnings.warn("Importing from numpy.matlib is deprecated since 1.19.0. "
  5. "The matrix subclass is not the recommended way to represent "
  6. "matrices or deal with linear algebra (see "
  7. "https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html). "
  8. "Please adjust your code to use regular ndarray. ",
  9. PendingDeprecationWarning, stacklevel=2)
  10. import numpy as np
  11. # Matlib.py contains all functions in the numpy namespace with a few
  12. # replacements. See doc/source/reference/routines.matlib.rst for details.
  13. # Need * as we're copying the numpy namespace.
  14. from numpy import * # noqa: F403
  15. from numpy.matrixlib.defmatrix import asmatrix, matrix
  16. __version__ = np.__version__
  17. __all__ = ['rand', 'randn', 'repmat']
  18. __all__ += np.__all__
  19. def empty(shape, dtype=None, order='C'):
  20. """Return a new matrix of given shape and type, without initializing entries.
  21. Parameters
  22. ----------
  23. shape : int or tuple of int
  24. Shape of the empty matrix.
  25. dtype : data-type, optional
  26. Desired output data-type.
  27. order : {'C', 'F'}, optional
  28. Whether to store multi-dimensional data in row-major
  29. (C-style) or column-major (Fortran-style) order in
  30. memory.
  31. See Also
  32. --------
  33. numpy.empty : Equivalent array function.
  34. matlib.zeros : Return a matrix of zeros.
  35. matlib.ones : Return a matrix of ones.
  36. Notes
  37. -----
  38. Unlike other matrix creation functions (e.g. `matlib.zeros`,
  39. `matlib.ones`), `matlib.empty` does not initialize the values of the
  40. matrix, and may therefore be marginally faster. However, the values
  41. stored in the newly allocated matrix are arbitrary. For reproducible
  42. behavior, be sure to set each element of the matrix before reading.
  43. Examples
  44. --------
  45. >>> import numpy.matlib
  46. >>> np.matlib.empty((2, 2)) # filled with random data
  47. matrix([[ 6.76425276e-320, 9.79033856e-307], # random
  48. [ 7.39337286e-309, 3.22135945e-309]])
  49. >>> np.matlib.empty((2, 2), dtype=int)
  50. matrix([[ 6600475, 0], # random
  51. [ 6586976, 22740995]])
  52. """
  53. return ndarray.__new__(matrix, shape, dtype, order=order)
  54. def ones(shape, dtype=None, order='C'):
  55. """
  56. Matrix of ones.
  57. Return a matrix of given shape and type, filled with ones.
  58. Parameters
  59. ----------
  60. shape : {sequence of ints, int}
  61. Shape of the matrix
  62. dtype : data-type, optional
  63. The desired data-type for the matrix, default is np.float64.
  64. order : {'C', 'F'}, optional
  65. Whether to store matrix in C- or Fortran-contiguous order,
  66. default is 'C'.
  67. Returns
  68. -------
  69. out : matrix
  70. Matrix of ones of given shape, dtype, and order.
  71. See Also
  72. --------
  73. ones : Array of ones.
  74. matlib.zeros : Zero matrix.
  75. Notes
  76. -----
  77. If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``,
  78. `out` becomes a single row matrix of shape ``(1,N)``.
  79. Examples
  80. --------
  81. >>> np.matlib.ones((2,3))
  82. matrix([[1., 1., 1.],
  83. [1., 1., 1.]])
  84. >>> np.matlib.ones(2)
  85. matrix([[1., 1.]])
  86. """
  87. a = ndarray.__new__(matrix, shape, dtype, order=order)
  88. a.fill(1)
  89. return a
  90. def zeros(shape, dtype=None, order='C'):
  91. """
  92. Return a matrix of given shape and type, filled with zeros.
  93. Parameters
  94. ----------
  95. shape : int or sequence of ints
  96. Shape of the matrix
  97. dtype : data-type, optional
  98. The desired data-type for the matrix, default is float.
  99. order : {'C', 'F'}, optional
  100. Whether to store the result in C- or Fortran-contiguous order,
  101. default is 'C'.
  102. Returns
  103. -------
  104. out : matrix
  105. Zero matrix of given shape, dtype, and order.
  106. See Also
  107. --------
  108. numpy.zeros : Equivalent array function.
  109. matlib.ones : Return a matrix of ones.
  110. Notes
  111. -----
  112. If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``,
  113. `out` becomes a single row matrix of shape ``(1,N)``.
  114. Examples
  115. --------
  116. >>> import numpy.matlib
  117. >>> np.matlib.zeros((2, 3))
  118. matrix([[0., 0., 0.],
  119. [0., 0., 0.]])
  120. >>> np.matlib.zeros(2)
  121. matrix([[0., 0.]])
  122. """
  123. a = ndarray.__new__(matrix, shape, dtype, order=order)
  124. a.fill(0)
  125. return a
  126. def identity(n, dtype=None):
  127. """
  128. Returns the square identity matrix of given size.
  129. Parameters
  130. ----------
  131. n : int
  132. Size of the returned identity matrix.
  133. dtype : data-type, optional
  134. Data-type of the output. Defaults to ``float``.
  135. Returns
  136. -------
  137. out : matrix
  138. `n` x `n` matrix with its main diagonal set to one,
  139. and all other elements zero.
  140. See Also
  141. --------
  142. numpy.identity : Equivalent array function.
  143. matlib.eye : More general matrix identity function.
  144. Examples
  145. --------
  146. >>> import numpy.matlib
  147. >>> np.matlib.identity(3, dtype=int)
  148. matrix([[1, 0, 0],
  149. [0, 1, 0],
  150. [0, 0, 1]])
  151. """
  152. a = array([1] + n * [0], dtype=dtype)
  153. b = empty((n, n), dtype=dtype)
  154. b.flat = a
  155. return b
  156. def eye(n, M=None, k=0, dtype=float, order='C'):
  157. """
  158. Return a matrix with ones on the diagonal and zeros elsewhere.
  159. Parameters
  160. ----------
  161. n : int
  162. Number of rows in the output.
  163. M : int, optional
  164. Number of columns in the output, defaults to `n`.
  165. k : int, optional
  166. Index of the diagonal: 0 refers to the main diagonal,
  167. a positive value refers to an upper diagonal,
  168. and a negative value to a lower diagonal.
  169. dtype : dtype, optional
  170. Data-type of the returned matrix.
  171. order : {'C', 'F'}, optional
  172. Whether the output should be stored in row-major (C-style) or
  173. column-major (Fortran-style) order in memory.
  174. Returns
  175. -------
  176. I : matrix
  177. A `n` x `M` matrix where all elements are equal to zero,
  178. except for the `k`-th diagonal, whose values are equal to one.
  179. See Also
  180. --------
  181. numpy.eye : Equivalent array function.
  182. identity : Square identity matrix.
  183. Examples
  184. --------
  185. >>> import numpy.matlib
  186. >>> np.matlib.eye(3, k=1, dtype=float)
  187. matrix([[0., 1., 0.],
  188. [0., 0., 1.],
  189. [0., 0., 0.]])
  190. """
  191. return asmatrix(np.eye(n, M=M, k=k, dtype=dtype, order=order))
  192. def rand(*args):
  193. """
  194. Return a matrix of random values with given shape.
  195. Create a matrix of the given shape and propagate it with
  196. random samples from a uniform distribution over ``[0, 1)``.
  197. Parameters
  198. ----------
  199. \\*args : Arguments
  200. Shape of the output.
  201. If given as N integers, each integer specifies the size of one
  202. dimension.
  203. If given as a tuple, this tuple gives the complete shape.
  204. Returns
  205. -------
  206. out : ndarray
  207. The matrix of random values with shape given by `\\*args`.
  208. See Also
  209. --------
  210. randn, numpy.random.RandomState.rand
  211. Examples
  212. --------
  213. >>> np.random.seed(123)
  214. >>> import numpy.matlib
  215. >>> np.matlib.rand(2, 3)
  216. matrix([[0.69646919, 0.28613933, 0.22685145],
  217. [0.55131477, 0.71946897, 0.42310646]])
  218. >>> np.matlib.rand((2, 3))
  219. matrix([[0.9807642 , 0.68482974, 0.4809319 ],
  220. [0.39211752, 0.34317802, 0.72904971]])
  221. If the first argument is a tuple, other arguments are ignored:
  222. >>> np.matlib.rand((2, 3), 4)
  223. matrix([[0.43857224, 0.0596779 , 0.39804426],
  224. [0.73799541, 0.18249173, 0.17545176]])
  225. """
  226. if isinstance(args[0], tuple):
  227. args = args[0]
  228. return asmatrix(np.random.rand(*args))
  229. def randn(*args):
  230. """
  231. Return a random matrix with data from the "standard normal" distribution.
  232. `randn` generates a matrix filled with random floats sampled from a
  233. univariate "normal" (Gaussian) distribution of mean 0 and variance 1.
  234. Parameters
  235. ----------
  236. \\*args : Arguments
  237. Shape of the output.
  238. If given as N integers, each integer specifies the size of one
  239. dimension. If given as a tuple, this tuple gives the complete shape.
  240. Returns
  241. -------
  242. Z : matrix of floats
  243. A matrix of floating-point samples drawn from the standard normal
  244. distribution.
  245. See Also
  246. --------
  247. rand, numpy.random.RandomState.randn
  248. Notes
  249. -----
  250. For random samples from the normal distribution with mean ``mu`` and
  251. standard deviation ``sigma``, use::
  252. sigma * np.matlib.randn(...) + mu
  253. Examples
  254. --------
  255. >>> np.random.seed(123)
  256. >>> import numpy.matlib
  257. >>> np.matlib.randn(1)
  258. matrix([[-1.0856306]])
  259. >>> np.matlib.randn(1, 2, 3)
  260. matrix([[ 0.99734545, 0.2829785 , -1.50629471],
  261. [-0.57860025, 1.65143654, -2.42667924]])
  262. Two-by-four matrix of samples from the normal distribution with
  263. mean 3 and standard deviation 2.5:
  264. >>> 2.5 * np.matlib.randn((2, 4)) + 3
  265. matrix([[1.92771843, 6.16484065, 0.83314899, 1.30278462],
  266. [2.76322758, 6.72847407, 1.40274501, 1.8900451 ]])
  267. """
  268. if isinstance(args[0], tuple):
  269. args = args[0]
  270. return asmatrix(np.random.randn(*args))
  271. def repmat(a, m, n):
  272. """
  273. Repeat a 0-D to 2-D array or matrix MxN times.
  274. Parameters
  275. ----------
  276. a : array_like
  277. The array or matrix to be repeated.
  278. m, n : int
  279. The number of times `a` is repeated along the first and second axes.
  280. Returns
  281. -------
  282. out : ndarray
  283. The result of repeating `a`.
  284. Examples
  285. --------
  286. >>> import numpy.matlib
  287. >>> a0 = np.array(1)
  288. >>> np.matlib.repmat(a0, 2, 3)
  289. array([[1, 1, 1],
  290. [1, 1, 1]])
  291. >>> a1 = np.arange(4)
  292. >>> np.matlib.repmat(a1, 2, 2)
  293. array([[0, 1, 2, 3, 0, 1, 2, 3],
  294. [0, 1, 2, 3, 0, 1, 2, 3]])
  295. >>> a2 = np.asmatrix(np.arange(6).reshape(2, 3))
  296. >>> np.matlib.repmat(a2, 2, 3)
  297. matrix([[0, 1, 2, 0, 1, 2, 0, 1, 2],
  298. [3, 4, 5, 3, 4, 5, 3, 4, 5],
  299. [0, 1, 2, 0, 1, 2, 0, 1, 2],
  300. [3, 4, 5, 3, 4, 5, 3, 4, 5]])
  301. """
  302. a = asanyarray(a)
  303. ndim = a.ndim
  304. if ndim == 0:
  305. origrows, origcols = (1, 1)
  306. elif ndim == 1:
  307. origrows, origcols = (1, a.shape[0])
  308. else:
  309. origrows, origcols = a.shape
  310. rows = origrows * m
  311. cols = origcols * n
  312. c = a.reshape(1, a.size).repeat(m, 0).reshape(rows, origcols).repeat(n, 0)
  313. return c.reshape(rows, cols)