Matrix in Python-Part1

Matrix in Python-Part1trainer.

cppBlockedUnblockFollowFollowingMay 17In this story and next few parts we will see what is matrix both mathematically and using them in Python.

We will build complete understanding of the concept from scratch.

This journey will be very fun and interesting if you write all code yourself as you read through and even if you have already some experience in python, I bet it will be very interesting if you stay tuned till the last part where we write everything the OOP way.

Python doesn’t have inbuilt support for matrices like languages that allow us to create multidimensional arrays (C, C++, Java etc.

).

Python provides similar behavior using nested lists.

In this part we start by constructing matrices with the list data structure provided by python to get basic idea on constructing matrices.

Later parts discuss operations, use of Numpy library, plus creating our own library for handling matrices.

ArraysConsider a sequence of four numbers.

 1 2 3 4Lets call it as A.

Now this thing A is usually called an Array and in python is represented by using list or a tuple.

This array A has length 4.

We will denote its length by n.

So for A, n = 4.

Below code shows example using both list and tuple.

In Python if I with to access or reference an individual element of this array, it is done using a number called index to denote position of that element in the array.

Indexes in Python start from zero so for above list/tuple since n=4 index of first element is 0 and that of last one is 3.

Below code prints all elements from the list using indexes.

Since normally size of a list(Array) in is not fixed so it is better to define operation on lists using python loops based on length of the list.

Below is the updated version of previous code.

You may use a while loop also but if you wish to re-write in a better and more pythonic way then see the written code below:For most of upcoming examples we will see one or the other ways of writing code to access matrix or array elements.

It is though important to know indexing to better understand matrix operations so more focus would be on loops that use indexes for any kind of matrix operations.

As a practice write code to print elements in reverse order.

MatricesA Matrix is a sequence of numbers that spans in two dimensions.

Unlike unlike arrays(also called as Vectors in Mathematics) which have a single dimension i.

e.

its length or size, a matrix has rows and columns.

A matrix looks like a rectangular block of numbers having m rows and n columns.

In mathematics a matrix looks like this.

M has 2 rows and 3 columns.

First row having [10 20 30] and first column having [10 -5].

It is important to visualize matrices as they are written in their mathematical treatment.

M is a 2 x 3(read as two cross three) matrix.

[Note: sometimes also referred as “two by three matrix”]In general a matrix is m x n (m cross n) dimensional.

m is number or rows(horizontal ones) and n is number of columns (verticals).

Accessing ElementsAccessing a single element or a Matrix requires you to specify both row and columns position.

So for referencing the element in first row and first column of matrix M we denote it as M and M₁₁ = 10In general the format is Mᵢⱼ where i is row number and j is column number.

In mathematical treatment the numbers (row and column numbers) start from 1 and not zero.

So the last element 40 will be referenced as M₂₃.

  Coming to Python.

To represent this in python we need to create a list of list.

To access elements we now need two indexes: one for outer list and other for inner.

Since indexes start from zero, so outer index ranges from 0–1 (row index) and inner index has range 0–2 (column index).

 So the first element(top left one) can be accessed as M[0][0] and last one as M[1][2] instead of M₁₁ and M₂₃ respectively.

To print number of rows and columns, use len() function.

For rows get len() of entire matrix M since number of rows is number of lists in outer list.

For columns check length of inner list.

To access one complete row say second row (i.

e.

index 1), do like this.

or if you print elements of second row individually thenPrinting a column wise is not that simple as the only way to access data is through indexes.

This is because of the way we have represented data in Python i.

e.

row wise.

So to print first column elements only way is:[Note: try to see what M[0][:] gives you]Element wise Access in PythonSee below code to print all elements of matrix M one by one in row major.

Above code uses nested for loops to print all elements row wise.

But the output doesn’t look like matrix.

To print in matrix format we need to use some features of print function.

See next code fragment.

If you don’t understand above nested loops, see the modified code below that prints indexes instead of the data.

This helps understand how indexes are getting manipulated.

Polishing our coding skillsLets update our code such that instead of putting values directly in code, I want to write a program to input the matrix dimensions and its data from user itself.

This can be done in many ways.

One way shown below takes data from user row by row.

You see that for each matrix that we are or will be creating, we will need to print it.

Let’s move the code to a function and make it reusable so that we don’t need to write same code to print again and again.

Similarly matrix input also can be moved in a function:It is a good idea to put the above 2 functions in a separate python script matrix.

py and put that script in the same folder as your Jupyter notebook or in same folder where your other scripts are present.

This allows you to import your code from matrix.

py and reuse these functions.

Then your previous code to input and print matrix will look like this:Lets add some more useful functions to our matrix.

py; functions to create matrices of zeroes and ones.

These functions will take shape of matrix and will create one with specific dimensions.

Normally the code to create a matrix of zeros would look like this:But this time I will use list comprehension to do so.

So the new code for creating matrices of zeros or ones with list comprehensions looks something like this:Similarly we define a function copy() to copy any matrix:Before going to our section lets go through what all is there in matrix.

py.

Right now it has functions to print and input matrices, create matrices of zeros and ones and also a method to create a copy of a matrix.

Make sure to complete your matrix.

py as we will use all these functions in upcoming sections.

Special MatricesBased on the dimension of matrices, we can have these special kind of matrices:Square MatrixA square matrix is one which has same number of rows and columns.

There are a few properties related to Square matrices that we will see in upcoming sections.

Row vectorRow vector is a matrix where number of columns is one.

i.

e.

a m x 1 matrix.

When writing with pen and paper, a row vector looks simply like this.

But representing using python lists can be a bit tricky.

Even though it can be represented just by using a single list.

But for our functions to be compatible, in python above has to be represented like this.

A list containing multiple lists with just one element.

Column VectorNow obviously a matrix with one single row, but multiple columns will become a Column Vector.

i.

e.

1 x mAgain for sake of compatibility we represent it in python as a list containing a single listNow lets look at some code to create these matrices.

You can use the functions we defined in previous sections to create row or column vectors of zeros and ones.

Output of previous code doesn’t look much like a matrix as it lacks the brackets, but that should be fine… at least it is for me as I am are more concerned about functionality.

If you wish to put some bracket around or as a DIY, you may put some effort on this task of displaying brackets around the matrix data.

It would be a different learning altogether.

For some help checkout the code below and run it in yourself.

And that’s it about the basics.

And with that your final matrix.

py will look like this:def print_matrix(mat): for i in range( len(mat) ): for j in range( len(mat[i]) ): print( mat[i][j] , end = ' ') print()def input_matrix(m, n): mat = [] for i in range(m): row = [] for j in range(n): num = input("Enter element (%d,%d):" % (i,j) ) row.

append(num) mat.

append(row) return matdef zeros(m,n): mat = []# TODO: Try putting in some dimension check for m and n.

for i in range(m): row = [] for j in range(n): row.

append(0) mat.

append(row) return matdef zeros(m,n): mat = [ [0 for j in range(n)] for i in range(m) ] return matdef ones(m,n): mat = [ [1 for j in range(n)] for i in range(m) ] return matdef copy(mat): return [ [data for data in row] for row in mat]Up next: Matrix in Python-Part2.

. More details

Leave a Reply