Technology3 min read

Creating Matrices with numpy.matrix() Function in Python

Abhishek Ahlawat

By Abhishek Ahlawat โ€” MAY 16, 2023

Founder of StudyTonight and a MERN fullstack developer. Writes about JavaScript, web development, Linux, and tech.

#python3-x#multidimensional-array#numpy

Summarize this article using AI

In this article, we will learn about the numpy.matrix() function, which is used to create a matrix from a given set of data. We will explore its parameters and understand how to use it with both string and array-like inputs.

numpy.matrix() Function:

The numpy.matrix() function is a class that allows us to create a specialized 2D array, which is known as a matrix. It takes a string of data or an array-like object as input and returns a matrix based on that data.

Parameters:

The numpy.matrix(data, dtype = None) function accepts the following parameters:

  • data : This parameter represents the data that needs to be provided as an array-like object or a string.

  • dtype : It is an optional parameter that specifies the data type of the array being returned.

Returns:

The numpy.matrix() function interprets the provided data and returns a matrix.

Example Code:

Now, let's look at an example to understand how to use the numpy.matrix() function.

# numpy.matrix class

import numpy as study

# string input
a = study.matrix('1 2 5 ; 3 4 6')
print("string input : \n", a, "\n")

# array-like input
b = study.matrix([[5, 6, 7], [4, 6, 6, 8]])
print("array-like input : \n", b)

Output :

After running the above code, we get the following output:


string input :
[[1 2 5]
[3 4 6]]

array-like input :
[[[5, 6, 7] [4, 6, 6, 8]]]

In the output, we can see the matrices created using the numpy.matrix() function. The first matrix is obtained from the string input, while the second matrix is obtained from the array-like input.

By using the numpy.matrix() function, we can easily create matrices from different types of input data, such as strings or arrays.

Spotted something outdated or wrong?

Liked this? See more StudyTonight posts in Google results.

Add StudyTonight as a preferred source
Next questLIVE OPSStep 2 / 3

Practice real incidents in the browser

System Design Ops โ€” put out fires, ship fixes, and stack XP. Reading done. Time to play.

Play System Design
  • +XP

    Every sim

  • Incidents

    Live ops

  • Ranks

    Climb up

Read next