NumPy – Matrix Library:
Matrix module contains the functions which return matrices instead of arrays.
matrix – This will return a matrix from an array kind of an object or from the string of data.
Example:
>>> x=np.matrix('1,2,3,4') >>> x matrix([[1, 2, 3, 4]]) >>> print(x) [[1 2 3 4]]
asmatrix – This will interpret the input as matrix.
Example:
>>> x=np.array([[1,2],[3,4],[4,5]]) >>> x array([[1, 2], [3, 4], [4, 5]]) >>> y=np.asmatrix(x) >>> y matrix([[1, 2], [3, 4], [4, 5]]) >>> x[0,0]=5 >>> y matrix([[5, 2], [3, 4], [4, 5]])
Below are the some replacement functions in matlib.
empty: This will return a new matrix of given shape and type.
Example:
>> import numpy.matlib as mb
# this will generate the random data
>>> mb.empty((2,2)) matrix([[ 4.00535364e-307, 2.33648882e-307], [ 3.44900029e-307, 1.78250172e-312]]) >>> mb.empty((2,2),int) matrix([[0, 1], [2, 3]]) >>> mb.empty((2,2),int) matrix([[1, 2], [3, 4]]) >>> mb.empty((2,2),int) matrix([[0, 1], [2, 3]])
zeros: This will return a matrix of given shape and type, filled with zeros.
Example:
>>> import numpy.matlib as mb >>> mb.zeros((3,3)) matrix([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]]) >>> mb.zeros((3,3),int) matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
ones: This will return a matrix of ones.
Example:
>>> import numpy.matlib as mb >>> mb.ones((3,3)) matrix([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]) >>> mb.ones((3,3),int) matrix([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
eye: This will return a matrix with ones on diagonal and zeros elsewhere.
Example:
>>> import numpy.matlib as mb >>> mb.eye(3) matrix([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> mb.eye(3,dtype=int) matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
identity: This will return a square identity matrix of given size.
Example:
>>> import numpy.matlib as mb >>> mb.identity(3,dtype=int) matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> mb.identity(4,dtype=int) matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
rand: This will return a matrix of random values with given shape.
Example:
>>> import numpy.matlib as mb >>> mb.rand(2,3) matrix([[ 0.76296068, 0.20586189, 0.18435659], [ 0.56268214, 0.47163051, 0.21750408]])
# if the first argument is tuple, Other arguments are ignored.
>>> mb.rand((2,3),int) matrix([[ 0.34026611, 0.35534349, 0.00456508], [ 0.32700061, 0.89152015, 0.74071634]])