Читать книгу Algorithms For Dummies - John Paul Mueller, John Mueller Paul, Luca Massaron - Страница 85
Creating a matrix is the right way to start
ОглавлениеMany of the same techniques you use with vectors also work with matrixes. To create a basic matrix, you simply use the array()
function as you would with a vector, but you define additional dimensions. A dimension is a direction in the matrix. For example, a two-dimensional matrix contains rows (one direction) and columns (a second direction). The array call myMatrix = np.array([[1,2,3], [4,5,6], [7,8,9]])
produces a matrix containing three rows and three columns, like this:
[[1 2 3] [4 5 6] [7 8 9]]
Note how you embed three lists within a container list to create the two dimensions. To access a particular array element, you provide a row and column index value, such as myMatrix[0, 0]
to access the first value of 1
. You can find a full listing of vector and matrix array-creation functions at https://numpy.org/doc/stable/reference/routines.array-creation.html
.
The NumPy package supports an actual matrix
class. The matrix
class supports special features that make it easier to perform matrix-specific tasks. You discover these features later in the chapter. For now, all you really need to know is how to create a matrix of the matrix
data type. The easiest method is to make a call similar to the one you use for the array
function, but using the mat
function instead, such as myMatrix = np.mat([[1,2,3], [4,5,6], [7,8,9]])
, which produces the following matrix:
[[1 2 3] [4 5 6] [7 8 9]]
To determine that this actually is a matrix, try print(type(myMatrix))
, which outputs <class 'numpy.matrix'>
. You can also convert an existing array to a matrix using the asmatrix()
function. Use the asarray()
function to convert a matrix
object back to an array
form.
The only problem with the matrix
class is that it works on only two-dimensional matrixes. If you attempt to convert a three-dimensional matrix to the matrix
class, you see an error message telling you that the shape is too large to be a matrix.