Sample code sharing for common operations in the Python matrix

Source: Internet
Author: User
This article mainly introduced the Python matrix Common operation operation, combined with the example form summarizes the Python matrix creation as well as the multiplication, the inverse, the transpose and so on related operation realization method, needs the friend to refer

This paper describes the common operation of Python matrix operations. Share to everyone for your reference, as follows:

Python's NumPy library provides the functionality of matrix operations, so we need to import numpy packages when we need matrix operations.

I. Import and use of NumPy


from numpy import *; #导入numpy的库函数import NumPy as NP; #这个方式使用numpy的函数时, need to start with NP.

Two. Creation of matrices

Create matrices from one-dimensional or two-dimensional data


From NumPy import *;a1=array ([]); A1=mat (A1);

Create a common matrix


Data1=mat (Zeros (3,3)); #创建一个3 0 matrix, the matrix here the Zeros function parameter is a tuple type (3,3) Data2=mat (Ones ((2,4))); #创建一个2 1 Matrix, The default is floating-point data and, if required, an int type, you can use Dtype=intdata3=mat (Random.rand (2,2)); #这里的random模块使用的是numpy中的random模块, Random.rand (2,2) Creates a two-dimensional array that needs to be converted to #matrixdata4=mat (Random.randint (10,size= (3,3))), and a random integer matrix between 0-10 of the #生成一个3. If you need to specify the nether, you can add one more parameter Data5=mat (Random.randint (2,8,size= (2,5)), random integer matrix Data6=mat between #产生一个2-8 (Eye (2,2,dtype=int)); Produces a 2*2 diagonal matrix A1=[1,2,3];a2=mat (diag (A1)); diagonal matrices of #生成一个对角线为1, 2, and 3

Three. Common matrix operations

1. Multiplication of matrices


A1=mat ([up]); A2=mat ([[[1],[2]]); a3=a1*a2; #1 The matrix multiplied by the 2*1 matrix to get the 1*1 matrix

2. Matrix Point Multiplication

Multiply matrix corresponding elements


A1=mat ([n]); A2=mat ([2,2]); a3=multiply (A1,A2);

Matrix Point Multiplication


A1=mat ([2,2]); a2=a1*2;

3. Matrix inversion, Transpose

Matrix inversion


A1=mat (Eye (2,2) *0.5); a2=a1. I; the inverse matrix of the #求矩阵matrix ([[0.5,0],[0,0.5]])

Matrix Transpose


A1=mat ([[1,1],[0,0]]); a2=a1. T

4. Calculate the maximum, minimum, and value of the matrix corresponding to the column.


A1=mat ([[1,1],[2,3],[4,2]]);

Calculate each column, row, and


A2=a1.sum (axis=0);//columns, here is 1*2 Matrix a3=a1.sum (Axis=1);//Line and, here is the 3*1 of the Matrix A4=sum (a1[1,:]);//Calculate the first row of all the columns of the and, here is a value

Calculate maximum, minimum, and index values


A1.max ();//calculate the maximum value of all the elements in the A1 matrix, the result is a numerical a2=max (a1[:,1]);//calculate the maximum value of the second column, here is a 1*1 matrix A1[1,:].max ();//calculate the maximum value of the second row, Here is a numerical np.max (a1,0);//calculates the maximum value of all columns, using the Max function Np.max (a1,1) in NumPy, and//calculates the maximum value of all rows, where the resulting is a matrix Np.argmax (a1,0);// Calculates the maximum value of all columns corresponding to the index in the column Np.argmax (a1[1,:]);//Calculates the index of the row in the second line that corresponds to the maximum value

5. Partitioning and merging of matrices

The separation of matrices is consistent with the separation of the list and array.


A=mat (Ones ((3,3))) b=a[1:,1:];//splits all elements of the second row after the row and the column after the second column

Merging of matrices


A=mat (Ones (2,2)); B=mat (Eye (2)); C=vstack ((b));//merge by column, that is, increase the number of rows D=hstack ((b));//merge by row, number of rows is unchanged, number of columns expanded

Four. Conversion of matrices, lists, and arrays

The list can be modified, and the elements in the list can make different types of data, as follows:


L1=[[1], ' Hello ', 3];

NumPy array, all elements in the same array must be of the same type, there are several common properties:


A=array ([[[2],[1]]);d The total number of imension=a.ndim;m,n=a.shape;number=a.size;//elements str=a.dtype;//element type

The matrices in NumPy also have several properties that are common to arrays.

The transitions between them:


a1=[[1,2],[3,2],[5,2]];//List A2=array (A1);//Convert the list to a two-dimensional array a3=array (A1);//Convert the list to a matrix A4=array (A3);//transform matrices into arrays a5=a3.tolist ();//convert Matrix to List a6=a2.tolist ();//convert Array to List

Here you can see that the conversion between the three is very simple, it is important to note that when the list is a one-dimensional, it is converted into arrays and matrices, and then through the ToList () conversion to the list is not the same, need to make some minor changes. As follows:


A1=[1,2,3];a2=array (A1); A3=mat (A1); a4=a2.tolist ();//What is obtained here is [1,2,3]a5=a3.tolist ();//What is obtained here is [[1,2,3]]a6=] (A4 = A5); /a6=falsea7= (A4 is a5[0]);//a7=true,a5[0]=[1,2,3]

The matrix is converted into a numeric value, and there is one of the following:


datamat=mat ([1]); val=datamat[0,0];//this time is the value of the element of the matrix, not the type of the matrix 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.