How to create matrix in Python | applied electronics engineering

Latest

How to create matrix in Python

By Applied Electronics - Tuesday, March 7, 2017 No Comments
 Here we show how you can create matrix with python programming language. First you should know there are two ways to create matrix in python- using python alone without any libraries and using python with numpy library/module or similar libraries. Here we will show how to create matrix using numpy. The advantage of using numpy package for numerical computation using matrix has many advantages so you should consider writing matrix using numpy. First and foremost, it is easy to create matrix using numpy, like creating matrix in matlab programming language. Second, it does not take long to install numpy. Whereas if you use python without numpy then you have to use list and loops which not only takes effort but also more lines and codes and it looks ugly.

If you don't already have numpy installed then just install it using the following command.

>> pip install numpy

Then depending upon whether you are using command prompt or python module you write the following import numpy command.

>> import numpy

Thats it! now you are ready to write your matrix.

To create a 3 by 3 matrix you write the following,

>>> A = numpy.array ( [ ( 1 , 2 , 3 ) , ( 4 , 5 , 6 ) , ( 2 , 7 , 8 ) ] )
>>> A
array ( [ [ 1 , 2 , 3 ] ,
          [ 4 , 5 , 6 ] ,
          [ 2 , 7 , 8 ] ] )

The array object of numpy has been used here.

What is the type of A matrix? A in numpy is called an ndarray object.

>>> type (A)
numpy.ndarray

For example in simply python language you create a list say a as follows,

>>>a = [ 1 , 2 , 3 ]
>>>a
[ 1 , 2 , 3 ]

The type of a is list,

>>>type ( a )
list

Similarly in numpy, A matrix created using array object is ndarray object type.

To create a single row vector you do the following,

>>>B = numpy . ar ray ( [ 1 , 2 , 3 ] )
>>>B
array ( [ 1 , 2 , 3 ] )
>>>type (B)
numpy.ndarray

For more see How to create multidimentional Numpy Array? and What are Python In-built Objects?

For a book on matrix using python see Python for Data Analysis PDF free download

No Comment to " How to create matrix in Python "