Python MatrixIn this article, we will introduce the Matrix with Python. We will implement each operation of matrix using the Python code. IntroductionA matrix is a rectangular 2-dimensional array which stores the data in rows and columns. The matrix can store any data type such as number, strings, expressions, etc. We must be familiar with the basic concepts of matrix before using it. The data is arranged in horizontal called rows, and vertical arrangements are columns. The number of elements inside a matrix is (R) X (C), where R is rows and C, columns. Python doesn't have a built-in type for matrices so that we will use the multiple lists as matrices. We will learn the following operations which are applied to the matrices.
Working of MatricesThe below matrix is 2x2, which means it has two rows and two columns. Creating a Matrix in PythonWe can create matrix in Python using the nested list. All elements are enclosed with the square brackets ([]) and separated by the comma. Let's see the following examples.
Read the Matrix DataIn the following example, we will read each row of the defined matrix. Example - Output: Read the Last Element from each rowIn the following example, we will read the last element of the each row using the Python program. Example - Output: 74 130 471 Explanation - In the above code, we have created a matrix, and we get the length of the matrix. We iterated each row using for loop and printed the result. We can read any row or column using the above method. Let's understand the following operation of the matrix. Adding two MatricesWe will add the two matrices and using the nested for loop through the given matrices. Example - Output: The sum of Matrix M1 and M2 = [[17, 29, 38], [20, 22, -1], [4, 6, 28]] Explanation -
Multiplication of Two MatricesMultiplication of the two matrices is the same as the above code, and only we need to change the operator + to *. Let's understand the following example. Example - Output: The sum of Matrix mat1 and mat2 = [[70, 208, -264], [99, 40, -12], [-5, 9, 27]] Transpose of MatrixA transpose is an operation where the given matrix's row is converted into a column and vice-versa. Let's understand the following example. Example - Output: [12, 4, 3] [7, 5, 8] Explanation In the above code, we have two for loop to iterate through each row and each column. As we can see that in above output, we assigned the mat1[i][j] and res[j][k]. Transpose Matrix Using List ComprehensionWe can use the list comprehension to transpose a matrix with one line of code. Let's understand the following example. Example - Output: [12, 4, 3] [7, 5, 8] The output is the same as above. The list comprehension reduced the lines of code and transposed the matrix. Take Matrix Input from the UserWe have discussed the pre-defined matrices so far. But what if user wants to enter their data. So we are defining the following example of a user-defined matrix. Example - Output: Enter the number of rows:3 Enter the number of columns:3 Enter the entries row wise: 5 6 7 8 9 2 4 3 1 5 6 7 8 9 2 4 3 1 Explanation - In the above code, we have taken the input from the user to enter number of rows and columns. We have entered the 3 rows and 3 columns; it means the matrix will have 9 elements. In for loop, the elements are inserted to the empty matrix using the append () function. The second for is loop used to print input data in the matrix format. Using the Numpy and map() function Python provides the external library Numpy. It is used for scientific computation; we will learn Numpy with matrix in below section. We will use it for the user input matrix. Example - Creating Matrix Using Numpy LibraryThe Numpy library helps us to work with the array. To work with the Numpy, we need to install the Numpy using the following command. After a successful installation, we have to import it into our program. Let's understand the following example. Example - Output: The matrix is: [[10 -5 15] [30 -6 91] [ 2 8 7]] Matrix Operation Using NumpyWe can perform all matrix operation using the numpy.array() such as addition, subtraction, transpose, slicing the matrix, etc. Matrix AdditionWe will create two matrices using the numpy.array() function and add them using the + operator. Let's understand the following example. Example - Output: The matrix addition is: [[ 16 -10 36] [ 14 21 50] [ 28 -16 60]] Matrix MultiplicationWe will use the mumpy.dot() method to multiply both matrices. It is a dot multiplication of the matrix mat1 and mat2 and handles the 2D array and performs multiplication. Let's understand the following example. Example - Output: The matrix is: [[ 78 128] [125 215]] Slicing of a MatrixWe can slice the matrix's element as we do in the Python standard list. Slicing returns the element based on the start/end index. We can also the negative slicing. The syntax is given below. Syntax - The arr represents the matrix name. By default the start index is 0, for example - [:3], it means start index is 0. If we do not provide the value to end, it will consider the length of the array. We can pass negative index values to both start and end. In the following example, we will apply slicing in normal array to understand how slicing works. Example - Output: [61 14 25] [10 40 61 14] [14 25 12 97] Now, we will implement slicing on matrix. To perform the slicing on matrix, follow the below syntax. Mat1[row_start:row_end, col_start:col_end] In the above syntax -
We will perform slicing in the below matrix. The above matrix consists of four rows. The 0th raw has [4, 10, 60, 18, 20], 1st row has [35, 16, 19, -12, 41] and so on. It has five columns. Let's understand the following example. Example - Output: [[ 16 19 -12] [ 80 42 24]] Explanation In the above example, we have printed the first and second rows, and we sliced the first, second, and third columns. According to the slicing syntax, we can get any rows and columns. Example - Print first row and all columnsOutput: [ 4 10 60 18 20]] Example - Print rows of the matrixOutput: [14 60 29] [ 35 -10 13] [ 4 8 12] ConclusionWe have discussed basic matrix using Python so far. We have learned to create matrix using a different approaches. Python matrix is a specialized two-dimensional rectangular list of data. The matrix can consist of a number, strings, expression, symbols, etc. Python doesn't provide a direct way to implement the matrix data type. We can create the matrix using the nested list and Numpy library. Next TopicPython Unit Testing
|
Python tutorial provides basic and advanced concepts of Python.
Vue.js is an open-source progressive JavaScript framework
HTML refers to Hypertext Markup Language. HTML is the gateway ...
Java is an object-oriented, class-based computer-programming language.
PHP is an open-source,interpreted scripting language.
Spring is a lightweight framework.Spring framework makes ...
JavaScript is an scripting language which is lightweight and cross-platform.
CSS refers to Cascading Style Sheets...
jQuery is a small and lightweight JavaScript library. jQuery ...
SQL is used to perform operations on the records stored in the database.
C programming is considered as the base for other programming languages.
JavaScript is an scripting language which is lightweight and cross-platform.
Vue.js is an open-source progressive JavaScript framework
ReactJS is a declarative, efficient, and flexible JavaScript library.
jQuery is a small and lightweight JavaScript library. jQuery ...
Node.js is a cross-platform environment and library for running JavaScript app...
TypeScript is a strongly typed superset of JavaScript which compiles to plain JavaScript.
Angular JS is an open source JavaScript framework by Google to build web app...
JSON is lightweight data-interchange format.
AJAX is an acronym for Asynchronous JavaScript and XML.
ES6 or ECMAScript 6 is a scripting language specification ...
Angular 7 is completely based on components.
jQuery UI is a set of user interface interactions built on jQuery...
Python tutorial provides basic and advanced concepts of Python.
Java is an object-oriented, class-based computer-programming language.
Node.js is a cross-platform environment and library for running JavaScript app...
PHP is an open-source,interpreted scripting language.
Go is a programming language which is developed by Google...
C programming is considered as the base for other programming languages.
C++ is an object-oriented programming language. It is an extension to C programming.
C# is a programming language of .Net Framework.
Ruby is an open-source and fully object-oriented programming language.
JSP technology is used to create web application just like Servlet technology.
The JSTL represents a set of tags to simplify the JSP development.
ASP.NET is a web framework designed and developed by Microsoft.
Perl is a cross-platform environment and library for running JavaScript...
Scala is an object-oriented and functional programming language.
VBA stands for Visual Basic for Applications.
Spring is a lightweight framework.Spring framework makes ...
Spring Boot is a Spring module that provides the RAD feature...
Django is a Web Application Framework which is used to develop web applications.
Servlet technology is robust and scalable because of java language.
The Struts 2 framework is used to develop MVC based web applications.
Hibernate is an open source, lightweight, ORM tool.
Solr is a scalable, ready-to-deploy enterprise search engine.
SQL is used to perform operations on the records stored in the database.
MySQL is a relational database management system based...
Oracle is a relational database management system.
SQL Server is software developed by Microsoft.
PostgreSQL is an ORDBMS.
DB2 is a database server developed by IBM.
Redis is a No SQL database which works on the concept of key-value pair.
SQLite is embedded relational database management system.
MongoDB is a No SQL database. It is an document-oriented database...
Memcached is a free, distributed memory object caching system.
Hibernate is an open source, lightweight, ORM tool.
PL/SQL is a block structured language that can have multiple blocks in it.
DBMS Tutorial is software that is used to manage the database.
Spark is a unified analytics engine for large-scale data processing...
IntelliJ IDEA is an IDE for Java Developers which is developed by...
Git is a modern and widely used distributed version control system in the world.
GitHub is an immense platform for code hosting.
SVN is an open-source centralized version control system.
Maven is a powerful project management tool that is based on POM.
Jsoup is a java html parser.
UML is a general-purpose, graphical modeling language.
RESTful Web Services are REST Architecture based Web Services.
Postman is one testing tools which is used for API testing.
JMeter is to analyze the performance of web application.
Jenkins builds and tests our software projects.
SEO stands for Search Engine Optimization.
MATLAB is a software package for mathematical computation, visualization...
Unity is an engine for creating games on multiple platforms.
Hadoop is an open source framework.
Pig is a high-level data flow platform for executing Map Reduce programs of Hadoop.
Spark is a unified analytics engine for large-scale data processing...
Spring Cloud is a framework for building robust cloud applications.
Spring Boot is a Spring module that provides the RAD feature...
AI is one of the fascinating and universal fields of Computer.
Cloud computing is a virtualization-based technology.
AWS stands for Amazon Web Services which uses distributed IT...
Microsoft Azure is a cloud computing platform...
IoT stands for Internet of Things...
Spring Cloud is a framework for building robust cloud applications.
Email:jjw.quan@gmail.com