matlib.py 10 KB

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