Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/numpy/matrixlib/defmatrix.py
7763 views
__all__ = ['matrix', 'bmat', 'mat', 'asmatrix']12import sys3import warnings4import ast5import numpy.core.numeric as N6from numpy.core.numeric import concatenate, isscalar7from numpy.core.overrides import set_module8# While not in __all__, matrix_power used to be defined here, so we import9# it for backward compatibility.10from numpy.linalg import matrix_power111213def _convert_from_string(data):14for char in '[]':15data = data.replace(char, '')1617rows = data.split(';')18newdata = []19count = 020for row in rows:21trow = row.split(',')22newrow = []23for col in trow:24temp = col.split()25newrow.extend(map(ast.literal_eval, temp))26if count == 0:27Ncols = len(newrow)28elif len(newrow) != Ncols:29raise ValueError("Rows not the same size.")30count += 131newdata.append(newrow)32return newdata333435@set_module('numpy')36def asmatrix(data, dtype=None):37"""38Interpret the input as a matrix.3940Unlike `matrix`, `asmatrix` does not make a copy if the input is already41a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``.4243Parameters44----------45data : array_like46Input data.47dtype : data-type48Data-type of the output matrix.4950Returns51-------52mat : matrix53`data` interpreted as a matrix.5455Examples56--------57>>> x = np.array([[1, 2], [3, 4]])5859>>> m = np.asmatrix(x)6061>>> x[0,0] = 56263>>> m64matrix([[5, 2],65[3, 4]])6667"""68return matrix(data, dtype=dtype, copy=False)697071@set_module('numpy')72class matrix(N.ndarray):73"""74matrix(data, dtype=None, copy=True)7576.. note:: It is no longer recommended to use this class, even for linear77algebra. Instead use regular arrays. The class may be removed78in the future.7980Returns a matrix from an array-like object, or from a string of data.81A matrix is a specialized 2-D array that retains its 2-D nature82through operations. It has certain special operators, such as ``*``83(matrix multiplication) and ``**`` (matrix power).8485Parameters86----------87data : array_like or string88If `data` is a string, it is interpreted as a matrix with commas89or spaces separating columns, and semicolons separating rows.90dtype : data-type91Data-type of the output matrix.92copy : bool93If `data` is already an `ndarray`, then this flag determines94whether the data is copied (the default), or whether a view is95constructed.9697See Also98--------99array100101Examples102--------103>>> a = np.matrix('1 2; 3 4')104>>> a105matrix([[1, 2],106[3, 4]])107108>>> np.matrix([[1, 2], [3, 4]])109matrix([[1, 2],110[3, 4]])111112"""113__array_priority__ = 10.0114def __new__(subtype, data, dtype=None, copy=True):115warnings.warn('the matrix subclass is not the recommended way to '116'represent matrices or deal with linear algebra (see '117'https://docs.scipy.org/doc/numpy/user/'118'numpy-for-matlab-users.html). '119'Please adjust your code to use regular ndarray.',120PendingDeprecationWarning, stacklevel=2)121if isinstance(data, matrix):122dtype2 = data.dtype123if (dtype is None):124dtype = dtype2125if (dtype2 == dtype) and (not copy):126return data127return data.astype(dtype)128129if isinstance(data, N.ndarray):130if dtype is None:131intype = data.dtype132else:133intype = N.dtype(dtype)134new = data.view(subtype)135if intype != data.dtype:136return new.astype(intype)137if copy: return new.copy()138else: return new139140if isinstance(data, str):141data = _convert_from_string(data)142143# now convert data to an array144arr = N.array(data, dtype=dtype, copy=copy)145ndim = arr.ndim146shape = arr.shape147if (ndim > 2):148raise ValueError("matrix must be 2-dimensional")149elif ndim == 0:150shape = (1, 1)151elif ndim == 1:152shape = (1, shape[0])153154order = 'C'155if (ndim == 2) and arr.flags.fortran:156order = 'F'157158if not (order or arr.flags.contiguous):159arr = arr.copy()160161ret = N.ndarray.__new__(subtype, shape, arr.dtype,162buffer=arr,163order=order)164return ret165166def __array_finalize__(self, obj):167self._getitem = False168if (isinstance(obj, matrix) and obj._getitem): return169ndim = self.ndim170if (ndim == 2):171return172if (ndim > 2):173newshape = tuple([x for x in self.shape if x > 1])174ndim = len(newshape)175if ndim == 2:176self.shape = newshape177return178elif (ndim > 2):179raise ValueError("shape too large to be a matrix.")180else:181newshape = self.shape182if ndim == 0:183self.shape = (1, 1)184elif ndim == 1:185self.shape = (1, newshape[0])186return187188def __getitem__(self, index):189self._getitem = True190191try:192out = N.ndarray.__getitem__(self, index)193finally:194self._getitem = False195196if not isinstance(out, N.ndarray):197return out198199if out.ndim == 0:200return out[()]201if out.ndim == 1:202sh = out.shape[0]203# Determine when we should have a column array204try:205n = len(index)206except Exception:207n = 0208if n > 1 and isscalar(index[1]):209out.shape = (sh, 1)210else:211out.shape = (1, sh)212return out213214def __mul__(self, other):215if isinstance(other, (N.ndarray, list, tuple)) :216# This promotes 1-D vectors to row vectors217return N.dot(self, asmatrix(other))218if isscalar(other) or not hasattr(other, '__rmul__') :219return N.dot(self, other)220return NotImplemented221222def __rmul__(self, other):223return N.dot(other, self)224225def __imul__(self, other):226self[:] = self * other227return self228229def __pow__(self, other):230return matrix_power(self, other)231232def __ipow__(self, other):233self[:] = self ** other234return self235236def __rpow__(self, other):237return NotImplemented238239def _align(self, axis):240"""A convenience function for operations that need to preserve axis241orientation.242"""243if axis is None:244return self[0, 0]245elif axis==0:246return self247elif axis==1:248return self.transpose()249else:250raise ValueError("unsupported axis")251252def _collapse(self, axis):253"""A convenience function for operations that want to collapse254to a scalar like _align, but are using keepdims=True255"""256if axis is None:257return self[0, 0]258else:259return self260261# Necessary because base-class tolist expects dimension262# reduction by x[0]263def tolist(self):264"""265Return the matrix as a (possibly nested) list.266267See `ndarray.tolist` for full documentation.268269See Also270--------271ndarray.tolist272273Examples274--------275>>> x = np.matrix(np.arange(12).reshape((3,4))); x276matrix([[ 0, 1, 2, 3],277[ 4, 5, 6, 7],278[ 8, 9, 10, 11]])279>>> x.tolist()280[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]281282"""283return self.__array__().tolist()284285# To preserve orientation of result...286def sum(self, axis=None, dtype=None, out=None):287"""288Returns the sum of the matrix elements, along the given axis.289290Refer to `numpy.sum` for full documentation.291292See Also293--------294numpy.sum295296Notes297-----298This is the same as `ndarray.sum`, except that where an `ndarray` would299be returned, a `matrix` object is returned instead.300301Examples302--------303>>> x = np.matrix([[1, 2], [4, 3]])304>>> x.sum()30510306>>> x.sum(axis=1)307matrix([[3],308[7]])309>>> x.sum(axis=1, dtype='float')310matrix([[3.],311[7.]])312>>> out = np.zeros((2, 1), dtype='float')313>>> x.sum(axis=1, dtype='float', out=np.asmatrix(out))314matrix([[3.],315[7.]])316317"""318return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis)319320321# To update docstring from array to matrix...322def squeeze(self, axis=None):323"""324Return a possibly reshaped matrix.325326Refer to `numpy.squeeze` for more documentation.327328Parameters329----------330axis : None or int or tuple of ints, optional331Selects a subset of the axes of length one in the shape.332If an axis is selected with shape entry greater than one,333an error is raised.334335Returns336-------337squeezed : matrix338The matrix, but as a (1, N) matrix if it had shape (N, 1).339340See Also341--------342numpy.squeeze : related function343344Notes345-----346If `m` has a single column then that column is returned347as the single row of a matrix. Otherwise `m` is returned.348The returned matrix is always either `m` itself or a view into `m`.349Supplying an axis keyword argument will not affect the returned matrix350but it may cause an error to be raised.351352Examples353--------354>>> c = np.matrix([[1], [2]])355>>> c356matrix([[1],357[2]])358>>> c.squeeze()359matrix([[1, 2]])360>>> r = c.T361>>> r362matrix([[1, 2]])363>>> r.squeeze()364matrix([[1, 2]])365>>> m = np.matrix([[1, 2], [3, 4]])366>>> m.squeeze()367matrix([[1, 2],368[3, 4]])369370"""371return N.ndarray.squeeze(self, axis=axis)372373374# To update docstring from array to matrix...375def flatten(self, order='C'):376"""377Return a flattened copy of the matrix.378379All `N` elements of the matrix are placed into a single row.380381Parameters382----------383order : {'C', 'F', 'A', 'K'}, optional384'C' means to flatten in row-major (C-style) order. 'F' means to385flatten in column-major (Fortran-style) order. 'A' means to386flatten in column-major order if `m` is Fortran *contiguous* in387memory, row-major order otherwise. 'K' means to flatten `m` in388the order the elements occur in memory. The default is 'C'.389390Returns391-------392y : matrix393A copy of the matrix, flattened to a `(1, N)` matrix where `N`394is the number of elements in the original matrix.395396See Also397--------398ravel : Return a flattened array.399flat : A 1-D flat iterator over the matrix.400401Examples402--------403>>> m = np.matrix([[1,2], [3,4]])404>>> m.flatten()405matrix([[1, 2, 3, 4]])406>>> m.flatten('F')407matrix([[1, 3, 2, 4]])408409"""410return N.ndarray.flatten(self, order=order)411412def mean(self, axis=None, dtype=None, out=None):413"""414Returns the average of the matrix elements along the given axis.415416Refer to `numpy.mean` for full documentation.417418See Also419--------420numpy.mean421422Notes423-----424Same as `ndarray.mean` except that, where that returns an `ndarray`,425this returns a `matrix` object.426427Examples428--------429>>> x = np.matrix(np.arange(12).reshape((3, 4)))430>>> x431matrix([[ 0, 1, 2, 3],432[ 4, 5, 6, 7],433[ 8, 9, 10, 11]])434>>> x.mean()4355.5436>>> x.mean(0)437matrix([[4., 5., 6., 7.]])438>>> x.mean(1)439matrix([[ 1.5],440[ 5.5],441[ 9.5]])442443"""444return N.ndarray.mean(self, axis, dtype, out, keepdims=True)._collapse(axis)445446def std(self, axis=None, dtype=None, out=None, ddof=0):447"""448Return the standard deviation of the array elements along the given axis.449450Refer to `numpy.std` for full documentation.451452See Also453--------454numpy.std455456Notes457-----458This is the same as `ndarray.std`, except that where an `ndarray` would459be returned, a `matrix` object is returned instead.460461Examples462--------463>>> x = np.matrix(np.arange(12).reshape((3, 4)))464>>> x465matrix([[ 0, 1, 2, 3],466[ 4, 5, 6, 7],467[ 8, 9, 10, 11]])468>>> x.std()4693.4520525295346629 # may vary470>>> x.std(0)471matrix([[ 3.26598632, 3.26598632, 3.26598632, 3.26598632]]) # may vary472>>> x.std(1)473matrix([[ 1.11803399],474[ 1.11803399],475[ 1.11803399]])476477"""478return N.ndarray.std(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis)479480def var(self, axis=None, dtype=None, out=None, ddof=0):481"""482Returns the variance of the matrix elements, along the given axis.483484Refer to `numpy.var` for full documentation.485486See Also487--------488numpy.var489490Notes491-----492This is the same as `ndarray.var`, except that where an `ndarray` would493be returned, a `matrix` object is returned instead.494495Examples496--------497>>> x = np.matrix(np.arange(12).reshape((3, 4)))498>>> x499matrix([[ 0, 1, 2, 3],500[ 4, 5, 6, 7],501[ 8, 9, 10, 11]])502>>> x.var()50311.916666666666666504>>> x.var(0)505matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) # may vary506>>> x.var(1)507matrix([[1.25],508[1.25],509[1.25]])510511"""512return N.ndarray.var(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis)513514def prod(self, axis=None, dtype=None, out=None):515"""516Return the product of the array elements over the given axis.517518Refer to `prod` for full documentation.519520See Also521--------522prod, ndarray.prod523524Notes525-----526Same as `ndarray.prod`, except, where that returns an `ndarray`, this527returns a `matrix` object instead.528529Examples530--------531>>> x = np.matrix(np.arange(12).reshape((3,4))); x532matrix([[ 0, 1, 2, 3],533[ 4, 5, 6, 7],534[ 8, 9, 10, 11]])535>>> x.prod()5360537>>> x.prod(0)538matrix([[ 0, 45, 120, 231]])539>>> x.prod(1)540matrix([[ 0],541[ 840],542[7920]])543544"""545return N.ndarray.prod(self, axis, dtype, out, keepdims=True)._collapse(axis)546547def any(self, axis=None, out=None):548"""549Test whether any array element along a given axis evaluates to True.550551Refer to `numpy.any` for full documentation.552553Parameters554----------555axis : int, optional556Axis along which logical OR is performed557out : ndarray, optional558Output to existing array instead of creating new one, must have559same shape as expected output560561Returns562-------563any : bool, ndarray564Returns a single bool if `axis` is ``None``; otherwise,565returns `ndarray`566567"""568return N.ndarray.any(self, axis, out, keepdims=True)._collapse(axis)569570def all(self, axis=None, out=None):571"""572Test whether all matrix elements along a given axis evaluate to True.573574Parameters575----------576See `numpy.all` for complete descriptions577578See Also579--------580numpy.all581582Notes583-----584This is the same as `ndarray.all`, but it returns a `matrix` object.585586Examples587--------588>>> x = np.matrix(np.arange(12).reshape((3,4))); x589matrix([[ 0, 1, 2, 3],590[ 4, 5, 6, 7],591[ 8, 9, 10, 11]])592>>> y = x[0]; y593matrix([[0, 1, 2, 3]])594>>> (x == y)595matrix([[ True, True, True, True],596[False, False, False, False],597[False, False, False, False]])598>>> (x == y).all()599False600>>> (x == y).all(0)601matrix([[False, False, False, False]])602>>> (x == y).all(1)603matrix([[ True],604[False],605[False]])606607"""608return N.ndarray.all(self, axis, out, keepdims=True)._collapse(axis)609610def max(self, axis=None, out=None):611"""612Return the maximum value along an axis.613614Parameters615----------616See `amax` for complete descriptions617618See Also619--------620amax, ndarray.max621622Notes623-----624This is the same as `ndarray.max`, but returns a `matrix` object625where `ndarray.max` would return an ndarray.626627Examples628--------629>>> x = np.matrix(np.arange(12).reshape((3,4))); x630matrix([[ 0, 1, 2, 3],631[ 4, 5, 6, 7],632[ 8, 9, 10, 11]])633>>> x.max()63411635>>> x.max(0)636matrix([[ 8, 9, 10, 11]])637>>> x.max(1)638matrix([[ 3],639[ 7],640[11]])641642"""643return N.ndarray.max(self, axis, out, keepdims=True)._collapse(axis)644645def argmax(self, axis=None, out=None):646"""647Indexes of the maximum values along an axis.648649Return the indexes of the first occurrences of the maximum values650along the specified axis. If axis is None, the index is for the651flattened matrix.652653Parameters654----------655See `numpy.argmax` for complete descriptions656657See Also658--------659numpy.argmax660661Notes662-----663This is the same as `ndarray.argmax`, but returns a `matrix` object664where `ndarray.argmax` would return an `ndarray`.665666Examples667--------668>>> x = np.matrix(np.arange(12).reshape((3,4))); x669matrix([[ 0, 1, 2, 3],670[ 4, 5, 6, 7],671[ 8, 9, 10, 11]])672>>> x.argmax()67311674>>> x.argmax(0)675matrix([[2, 2, 2, 2]])676>>> x.argmax(1)677matrix([[3],678[3],679[3]])680681"""682return N.ndarray.argmax(self, axis, out)._align(axis)683684def min(self, axis=None, out=None):685"""686Return the minimum value along an axis.687688Parameters689----------690See `amin` for complete descriptions.691692See Also693--------694amin, ndarray.min695696Notes697-----698This is the same as `ndarray.min`, but returns a `matrix` object699where `ndarray.min` would return an ndarray.700701Examples702--------703>>> x = -np.matrix(np.arange(12).reshape((3,4))); x704matrix([[ 0, -1, -2, -3],705[ -4, -5, -6, -7],706[ -8, -9, -10, -11]])707>>> x.min()708-11709>>> x.min(0)710matrix([[ -8, -9, -10, -11]])711>>> x.min(1)712matrix([[ -3],713[ -7],714[-11]])715716"""717return N.ndarray.min(self, axis, out, keepdims=True)._collapse(axis)718719def argmin(self, axis=None, out=None):720"""721Indexes of the minimum values along an axis.722723Return the indexes of the first occurrences of the minimum values724along the specified axis. If axis is None, the index is for the725flattened matrix.726727Parameters728----------729See `numpy.argmin` for complete descriptions.730731See Also732--------733numpy.argmin734735Notes736-----737This is the same as `ndarray.argmin`, but returns a `matrix` object738where `ndarray.argmin` would return an `ndarray`.739740Examples741--------742>>> x = -np.matrix(np.arange(12).reshape((3,4))); x743matrix([[ 0, -1, -2, -3],744[ -4, -5, -6, -7],745[ -8, -9, -10, -11]])746>>> x.argmin()74711748>>> x.argmin(0)749matrix([[2, 2, 2, 2]])750>>> x.argmin(1)751matrix([[3],752[3],753[3]])754755"""756return N.ndarray.argmin(self, axis, out)._align(axis)757758def ptp(self, axis=None, out=None):759"""760Peak-to-peak (maximum - minimum) value along the given axis.761762Refer to `numpy.ptp` for full documentation.763764See Also765--------766numpy.ptp767768Notes769-----770Same as `ndarray.ptp`, except, where that would return an `ndarray` object,771this returns a `matrix` object.772773Examples774--------775>>> x = np.matrix(np.arange(12).reshape((3,4))); x776matrix([[ 0, 1, 2, 3],777[ 4, 5, 6, 7],778[ 8, 9, 10, 11]])779>>> x.ptp()78011781>>> x.ptp(0)782matrix([[8, 8, 8, 8]])783>>> x.ptp(1)784matrix([[3],785[3],786[3]])787788"""789return N.ndarray.ptp(self, axis, out)._align(axis)790791@property792def I(self):793"""794Returns the (multiplicative) inverse of invertible `self`.795796Parameters797----------798None799800Returns801-------802ret : matrix object803If `self` is non-singular, `ret` is such that ``ret * self`` ==804``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return805``True``.806807Raises808------809numpy.linalg.LinAlgError: Singular matrix810If `self` is singular.811812See Also813--------814linalg.inv815816Examples817--------818>>> m = np.matrix('[1, 2; 3, 4]'); m819matrix([[1, 2],820[3, 4]])821>>> m.getI()822matrix([[-2. , 1. ],823[ 1.5, -0.5]])824>>> m.getI() * m825matrix([[ 1., 0.], # may vary826[ 0., 1.]])827828"""829M, N = self.shape830if M == N:831from numpy.linalg import inv as func832else:833from numpy.linalg import pinv as func834return asmatrix(func(self))835836@property837def A(self):838"""839Return `self` as an `ndarray` object.840841Equivalent to ``np.asarray(self)``.842843Parameters844----------845None846847Returns848-------849ret : ndarray850`self` as an `ndarray`851852Examples853--------854>>> x = np.matrix(np.arange(12).reshape((3,4))); x855matrix([[ 0, 1, 2, 3],856[ 4, 5, 6, 7],857[ 8, 9, 10, 11]])858>>> x.getA()859array([[ 0, 1, 2, 3],860[ 4, 5, 6, 7],861[ 8, 9, 10, 11]])862863"""864return self.__array__()865866@property867def A1(self):868"""869Return `self` as a flattened `ndarray`.870871Equivalent to ``np.asarray(x).ravel()``872873Parameters874----------875None876877Returns878-------879ret : ndarray880`self`, 1-D, as an `ndarray`881882Examples883--------884>>> x = np.matrix(np.arange(12).reshape((3,4))); x885matrix([[ 0, 1, 2, 3],886[ 4, 5, 6, 7],887[ 8, 9, 10, 11]])888>>> x.getA1()889array([ 0, 1, 2, ..., 9, 10, 11])890891892"""893return self.__array__().ravel()894895896def ravel(self, order='C'):897"""898Return a flattened matrix.899900Refer to `numpy.ravel` for more documentation.901902Parameters903----------904order : {'C', 'F', 'A', 'K'}, optional905The elements of `m` are read using this index order. 'C' means to906index the elements in C-like order, with the last axis index907changing fastest, back to the first axis index changing slowest.908'F' means to index the elements in Fortran-like index order, with909the first index changing fastest, and the last index changing910slowest. Note that the 'C' and 'F' options take no account of the911memory layout of the underlying array, and only refer to the order912of axis indexing. 'A' means to read the elements in Fortran-like913index order if `m` is Fortran *contiguous* in memory, C-like order914otherwise. 'K' means to read the elements in the order they occur915in memory, except for reversing the data when strides are negative.916By default, 'C' index order is used.917918Returns919-------920ret : matrix921Return the matrix flattened to shape `(1, N)` where `N`922is the number of elements in the original matrix.923A copy is made only if necessary.924925See Also926--------927matrix.flatten : returns a similar output matrix but always a copy928matrix.flat : a flat iterator on the array.929numpy.ravel : related function which returns an ndarray930931"""932return N.ndarray.ravel(self, order=order)933934@property935def T(self):936"""937Returns the transpose of the matrix.938939Does *not* conjugate! For the complex conjugate transpose, use ``.H``.940941Parameters942----------943None944945Returns946-------947ret : matrix object948The (non-conjugated) transpose of the matrix.949950See Also951--------952transpose, getH953954Examples955--------956>>> m = np.matrix('[1, 2; 3, 4]')957>>> m958matrix([[1, 2],959[3, 4]])960>>> m.getT()961matrix([[1, 3],962[2, 4]])963964"""965return self.transpose()966967@property968def H(self):969"""970Returns the (complex) conjugate transpose of `self`.971972Equivalent to ``np.transpose(self)`` if `self` is real-valued.973974Parameters975----------976None977978Returns979-------980ret : matrix object981complex conjugate transpose of `self`982983Examples984--------985>>> x = np.matrix(np.arange(12).reshape((3,4)))986>>> z = x - 1j*x; z987matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j],988[ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j],989[ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]])990>>> z.getH()991matrix([[ 0. -0.j, 4. +4.j, 8. +8.j],992[ 1. +1.j, 5. +5.j, 9. +9.j],993[ 2. +2.j, 6. +6.j, 10.+10.j],994[ 3. +3.j, 7. +7.j, 11.+11.j]])995996"""997if issubclass(self.dtype.type, N.complexfloating):998return self.transpose().conjugate()999else:1000return self.transpose()10011002# kept for compatibility1003getT = T.fget1004getA = A.fget1005getA1 = A1.fget1006getH = H.fget1007getI = I.fget10081009def _from_string(str, gdict, ldict):1010rows = str.split(';')1011rowtup = []1012for row in rows:1013trow = row.split(',')1014newrow = []1015for x in trow:1016newrow.extend(x.split())1017trow = newrow1018coltup = []1019for col in trow:1020col = col.strip()1021try:1022thismat = ldict[col]1023except KeyError:1024try:1025thismat = gdict[col]1026except KeyError as e:1027raise NameError(f"name {col!r} is not defined") from None10281029coltup.append(thismat)1030rowtup.append(concatenate(coltup, axis=-1))1031return concatenate(rowtup, axis=0)103210331034@set_module('numpy')1035def bmat(obj, ldict=None, gdict=None):1036"""1037Build a matrix object from a string, nested sequence, or array.10381039Parameters1040----------1041obj : str or array_like1042Input data. If a string, variables in the current scope may be1043referenced by name.1044ldict : dict, optional1045A dictionary that replaces local operands in current frame.1046Ignored if `obj` is not a string or `gdict` is None.1047gdict : dict, optional1048A dictionary that replaces global operands in current frame.1049Ignored if `obj` is not a string.10501051Returns1052-------1053out : matrix1054Returns a matrix object, which is a specialized 2-D array.10551056See Also1057--------1058block :1059A generalization of this function for N-d arrays, that returns normal1060ndarrays.10611062Examples1063--------1064>>> A = np.mat('1 1; 1 1')1065>>> B = np.mat('2 2; 2 2')1066>>> C = np.mat('3 4; 5 6')1067>>> D = np.mat('7 8; 9 0')10681069All the following expressions construct the same block matrix:10701071>>> np.bmat([[A, B], [C, D]])1072matrix([[1, 1, 2, 2],1073[1, 1, 2, 2],1074[3, 4, 7, 8],1075[5, 6, 9, 0]])1076>>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])1077matrix([[1, 1, 2, 2],1078[1, 1, 2, 2],1079[3, 4, 7, 8],1080[5, 6, 9, 0]])1081>>> np.bmat('A,B; C,D')1082matrix([[1, 1, 2, 2],1083[1, 1, 2, 2],1084[3, 4, 7, 8],1085[5, 6, 9, 0]])10861087"""1088if isinstance(obj, str):1089if gdict is None:1090# get previous frame1091frame = sys._getframe().f_back1092glob_dict = frame.f_globals1093loc_dict = frame.f_locals1094else:1095glob_dict = gdict1096loc_dict = ldict10971098return matrix(_from_string(obj, glob_dict, loc_dict))10991100if isinstance(obj, (tuple, list)):1101# [[A,B],[C,D]]1102arr_rows = []1103for row in obj:1104if isinstance(row, N.ndarray): # not 2-d1105return matrix(concatenate(obj, axis=-1))1106else:1107arr_rows.append(concatenate(row, axis=-1))1108return matrix(concatenate(arr_rows, axis=0))1109if isinstance(obj, N.ndarray):1110return matrix(obj)11111112mat = asmatrix111311141115