Scalars, Vector and Matrices in Python (Using Arrays)

Arrays in python, are frequently used to work with scalars, vectors and matrices, a topic of today’s post. This post is continuation of linear algebra for data science.

We use NumPy, a library for the python programming which allows us to work with multidimensional arrays and matrices along with a large collection of high-level mathematical functions to operate on these arrays. let’s start a practical example,

import numpy as np

Declaring Scalar, Vectors and Matrices

declaring scalars in python

As you have already known that scalar has no dimension and the above example showed how to declare a scalar quantity in python. Now in the next example, we are going to declare a new variable i.e. vector which is equal to an array of 2, 4 and 6 which are enclosed by a bracket like this,

declaring vectors in python

Now we are going to declare a Matrix having two rows and three columns. The elements of each row are enclosed by a bracket and the two brackets are separated by a comma, whereas, these two rows are enclosed by a whole bracket, result of which is given below,

declaring matrix in python

Data Types

If we intend to get the data type of any variable like previously declared as scalar, vector and matrix then we simply write type and variable name which enclosed by a bracket as shown in given picture,

data types in declaring scalar, matrix and vector

In above example, vector is a one-dimensional array and matrix is a two-dimensional array. It is pertinent to mention here that within numpy, integers, floats and arrays with one element perform in the same way as regards linear algebraic operations.

Data Shapes

Shape can also apply to our objects to confirm their dimensionality or shape like this,

data shapes of vector and matrix in python

It is cleared from above snap that the first matrix has three rows and one column i.e. (3,), whereas, the second matrix has two rows and three columns i.e. (2, 3).

Create a column vector

Here, we use a reshape method which provides an array with a new shape without altering its data like this,

create a new column vector without altering its data in python

You can see that the resultant matrix contains three rows and one column which was previously contained only one row and three columns.

Read also: Introduction to Data Science (A Beginner’s Guide)

Leave a Comment