How to create matrix in python

How to Create a Matrix in Python

How to Create a Matrix in Python | Here, we will discuss how to create a matrix in python? A matrix is a rectangular table arranged in the form of rows and columns. In the programming world, we implement a matrix by using arrays by classifying them as 1D and 2D arrays. In this section, there are some examples to create a matrix in python. Also See:- List in Python MCQ

  1. How To Create Matrix In Python Using Numpy
  2. How To Create A Matrix In Python Without Numpy
  3. How To Create A Matrix In Python Using For Loop
  4. How To Create An Empty Matrix In Python
  5. How To Create A Zero Matrix In Python
  6. How To Create A 2d Matrix In Python
  7. How To Create A 3×3 Identity Matrix In Python
Читайте также:  Java print string with format

How to Create a Matrix in Python using NumPy

In the Python programming language, NumPy is a library that supports single and multi-dimensional arrays, matrices, and a large collection of high-level mathematical functions to operate on these arrays and matrices. It contains lots of pre-defined functions which can be called on these matrices and it will simplify our task.

Make a Matrix in Python Using NumPy.array()

Now let us see a simple program to create/make a matrix in Python using NumPy. In this code, we will use numpy.array() to make/create a matrix. NumPy.array() returns an array object satisfying the specified requirements given in the parameter.

import numpy as np num = np.array([[1, 1, 2], [3, 5, 3], [5, 6, 9]]) print(num)

In the above code, we have imported NumPy as np , then in variable num , we stored an array by using the function numpy.array(). However, we can do this in a mathematical way also but it would be a long sequence. That is why using the NumPy library can be a better way of coding in the Python programming language, and makes our task very easy.

Python Create a Matrix Using NumPy.matrix()

The numpy.matrix() is also a function in NumPy that is used to return an array, it works very similarly to numpy.array().

import numpy as np num = np.matrix(([1, 1, 1], [15, 34, 3], [50, 69, 99])) print(num)

Create a Matrix in Python Using NumPy.reshape()

The numpy.reshape() is a function in NumPy that converts a 1D array to 2D.

import numpy as np num = np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9]]).reshape(3, 3) print(num)

The reshape() function takes 2 parameters that are row and column. It is basically used to alter the size of the array. In the above example reshape() takes 2 parameters 3 and 3 so it converts 1D array to 2D array 3X3 elements.

Читайте также:  Php mysql таблица пользователей

Make a Matrix in Python Using NumPy.append()

The numpy.append() function appends an array into the row. It will append values to the end of an array.

import numpy as np num = np.array([[5, 7, 8]]) new = np.append(num, [[4, 5, 6], [4, 9, 0], [2, 3, 1]], axis=0) print(new)

In the above code, the array num is appended to new so the array gets altered. The axis parameter is set 0 as we wish to append the elements as rows. We have also used shape as it displays the dimension of the matrix. In the above example, we have created a matrix with 4 rows and 3 columns hence dimension is (4,3).

How to Create a Matrix in Python Without NumPy

NumPy library contains various methods to create a matrix but it also can be created without using NumPy. The below code creates a 2D matrix using the nested list. A nested list is a list within a list.

m = [[5, 3, 7], [7, 6, 7], [1, 6, 0]] for i in m: print(i) 

In the example shown we have declared variable m as a nested list and then used a for loop to print all the elements, without a for loop the elements have been printed in a single line.

We can do this by using a join function

m = ([5, 3, 7], [7, 6, 7], [1, 6, 0]) for i in m: print("". join(str(i)))

The above shown both examples give the same output but the difference is join() function joins the elements of a row into a single string before printing it.

How to Create a Matrix in Python Using For Loop

We can also use for loop to create a matrix.

Step 1: We have first a single list mat
Step 2: Then we iterate by for loop to print it twice using a range within the list it will change into nested list acting as a matrix

mat = [[3, 8, 9] for i in range(2)] for i in mat: print("".join(str(i)))

In the above output, we have printed the list twice by giving the range parameter as 2.

How to Create an Empty Matrix in Python

In the below-shown example we have used a library called NumPy, there are many inbuilt functions in NumPy which makes coding easy. Here we have used one such function called empty() which creates an empty matrix.

import numpy as np emp = np.empty((0, 4)) print(emp)

The above code has created a matrix with 0 rows and 4 columns.

How to Create a Zero Matrix in Python

A zero matrix is a matrix that contains all 0 elements. The zeros() is a function in the NumPy library that creates a zero matrix, here dtype is used to specify the data type of the elements.

import numpy as np mat = np.zeros([2, 2], dtype=int) print(mat)

The above code creates a zero matrix with 2 rows and 2 columns.

How to Create a 2D Matrix in Python

We can create a 2D matrix in python by using a nested list.

m = [[4, 1, 2], [7, 5, 3], [9, 6, 9]] for i in m: print("".join(str(i)))

The above output shows a 2-dimensional matrix.

How to Create a 3X3 Identity Matrix in Python

A 3X3 matrix is a matrix that has 3 rows and 3 columns, and an identity matrix is a matrix whose diagonal elements are always 1. The function np.identity() itself creates a identity matrix of 3 rows and 3 columns.

import numpy as np a = np.identity(3) print(a)

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

Create matrix in Python

Create matrix in Python

In the world of programming, matrices are represented as 2-D arrays used for data representation in rows and columns. These are used in various mathematical and statistical operations and they retain their shape. A matrix with an equal number of rows and columns is called a square matrix.

To create matrix in Python, we can use the numpy arrays or lists. We will discuss how to create matrix in Python in this article.

Using lists to create matrix in Python

A list also stores a collection of elements at particular positions. A list can store elements of different types under a single list and mathematical operations cannot be applied directly to a list.

We can use it to create matrix in Python.

Using the nested lists to create matrix

A nested list is a list within a list and can be used to create matrix in Python.

A very simple example is shown below.

In the above example, we created a simple nested list that represents a matrix.

Note that we did not print the list directly. This is done because that will print the list in a single line. That is why we iterate through every row individually. We can also do this more cleanly with the join() function.

The difference in using this method to print a matrix is that it joins the elements of a row into a single string before printing it.

Further reading:

Initialize matrix in Python
Print matrix in Python

Using the for loop to create matrix

We can use the for loop to create matrix in Python using lists in Python. If we have a single list then we can iterate it the required number of times within the list, and it will change to a nested list acting as a matrix.

This method takes a single list and changes it to a matrix of the required shape.

There is another way to use the for loop to create matrix in Python.

  • We first initialized two empty lists. One will act like a row and the other will act as the final matrix.
  • We run a nested loop. The inner loop adds an element to the list lst .
  • In the outer loop, lst gets appended to the matrix list m as a row.
  • We then initialize the lst as an empty list and the loop runs again for the next row.

This method is very convenient if we wish to take the input from the user for every element in a list. For this, we have to simply ask for the input in the inner loop before appending the element to the lst list.

The final list discussed in the above examples can be directly converted to a numpy array using the numpy.array() or the numpy.matrix() function. These methods will be discussed below.

Using numpy arrays to create matrix in Python

A numpy array is used to store a collection of elements of the same type. However, we can apply mathematical operations directly to an array and they can store a longer sequence of data efficiently. That is why it is considered a better approach to use numpy arrays for matrices in Python.

Let us discuss different methods to create matrix in Python using numpy arrays.

Using the numpy.array() function to create matrix in Python

We can create a 2-D numpy array using the numpy.array() function in Python.

Источник

Оцените статью