Write a Basic Matrix in Python

Write a Basic Matrix in Python

The Matrix has you...

·

2 min read

This article will help you write a very basic matrix in Python using the popular PyTorch Library

What is Matrix?

Well what is matrix in the first place?

Matrix according to Mathematics is a rectangular array of numbers, symbols or expressions arranged in rows and columns.

If you have a background in programming, arrays might have already been familiar to you. But if you are a beginner I suggest you watch the basics of arrays.

Basic Array

Array( or List) is one of the data structures where you will get to store more complex data (including string, numbers, object etc).

Arrays typically include square brackets to enclose the data it holds and it's almost linear in structure.

emojis = ["❤️","✅", "🔥", "😊", "😂"]

Arrays typically has an index attached to it starting from 0. The index is how the each element in the array is identified. Think of it like like an id field of an SQL Table.

print(emojis[0])
❤️
print(emojis[3])
😊

Since it's a array with short length, we know the number of elements is 5, so the index runs from 0 to 4. But let's see how we can programmatically find the length of any array.

Len function is an in-built python function which will help in this process.

print(len(emojis))
5

Let's evaluate a Matrix

Matrix as given in the above definition is a rectangular array of elements. So the shape of the matrix will not be identical like in the case of Square arrays.

In a programmer's world, this is basically array of arrays. Now that we have a basic understanding, let's tackle this step by step.

 [[],
  []]

Importing Pytorch

First import pytorch using the following command

import torch

Access tensor method

The Torch Class involves a method called 'tensor' which makes it easy for us to build a matrix

But here's the take torch.Tensor typically accepts only integers and floats but not strings

matrix = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(matrix)

Exploring Dimensions

We can evaluate the dimensions of any matrix we construct using the ndim method

matrix.ndim
2

Shape of a Matrix

We can evaluate the shape of any matrix using the shape method

matrix.shape
torch.Size([2, 3])

The 'matrix' variable holds a 2 X 3 shaped matrix which can be visualized more eloquently

torch.tensor([
[1, 2, 3], 
[4, 5, 6]]
)

2 stands for no of rows and 3 for no of columns

This is how we can create a basic matrix in Python using PyTorch.