Team Ai
Datasetpublic

codekingpro/portable-devtools

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