# Python for MATLAB Users

When we move from our academics into the industry, especially engineering individuals, we face a very common problem that we are mainly taught about the obsolete or near obsolete technologies. For example, many schools still use MATLAB. In the engineering sector, whether it is chemical engineer, electrical engineer, or nanoengineer, everyone must have used MATLAB.

But in recent times, we can see businesses are shifting from MATLAB to Python. This can be due to a variety of reasons −

• \$1000 licensing cost

• Inefficient memory allocation

• Dearth of open source libraries

• Detest MATLAB syntax.

The people who want to switch from MATLAB to Python should not worry much as their syntaxes are nearly similar.

Let us address the fundamentals of Python for MATLAB users with an emphasis on data analytics and visualization.

## Facilities for Matrix Users

Numpy includes a few features that make it easier to use the matrix type, which should help MATLAB convert.

• There is now a matlib module that includes matrices for popular array constructors like

zeros(), ones(), empty(), rand(), eye(), and repmat()

• An array can now be converted to a matrix without copying the data because mat is a synonym for asmatrix rather than a matrix.

• There have been some top-level functions eliminated. As an illustration, numpy.rand() must be accessed as numpy.random.rand(). Alternately, use the matlib module's rand() method. However, using numpy.random.random(), which, like other numpy functions, accepts a tuple for the shape, is the "numpythonic" method

For the people who understand simple MATLAB syntax, we can use the following −

mat = np.matrix('2,6,3;  0,2,5;  1,7,4')


But in Python logic, we use vectors or lists. Hence, the following syntax will be equivalent −

mat = np.matrix([[2,6,3], [0,2,5], [1,7,4]])


Using the Python language syntax, we can easily traverse, and get values.

For example,

### Example

If we want to get the first, i.e., (0,0) value we can simply write mat[0,0]

import numpy as np
mat = np.matrix([
[2,6,3],
[0,2,5],
[1,7,4]
])
print(mat[0,0])


### Output

2


### Example

First column can be accessed as mat[: , 0]

import numpy as np
mat = np.matrix([
[2,6,3],
[0,2,5],
[1,7,4]
])
print(mat[: , 0])


### Output

[[2]
[0]
[1]]


### Example

Accessing Just the first row as −

import numpy as np
mat = np.matrix([
[2,6,3],
[0,2,5],
[1,7,4]
])
print(mat[0,:])


### Output

[[2 6 3]]


## MATLAB-NumPy Equivalents

### Submatrix

The ix_ command can be used to assign data to a submatrix using lists of indexes.

For instance, one may enter

index=[1,2];
matrix[np.ix_(index,index)]+=100


for the 2D array matrix.

### Example

import numpy as np
mat = np.matrix([
[2,6,3],
[0,2,5],
[1,7,4]
])
index=[1,2];
mat[np.ix_(index,index)]+=100
print(mat)


### Output

[[ 2 6 3]
[ 0 102 105]
[ 1 107 104]]


### Help

Although MATLAB lacks a direct equivalent of the which command, the source and help command frequently show the filename of the location where the function is being stored.

Additionally, Python includes an inspect module (to use this module, import inspect), which offers an often functional getfile.

### Indexing

The first element of any array/sequence has index 1 because MATLAB utilizes 1-based indexing.

The first element of any array/sequence has index zero since Python utilizes 0-based indexing.

### Ranges

In Python, a construct like 0:5 can only be used as a slice index; in MATLAB, 0:5 can be used as both a "slice" index (inside square brackets) and a range literal (within parentheses).

As a result, the oddball r_ object was developed so that Numpy could have a similarly succinct range creation method.

Because r_ object is indexed using square brackets rather than being called like a function or function Object() { [native code] }, slice syntax can be used in the parameters.

### Logicops

In MATLAB, | and & are logical AND/OR, whereas in NumPy, & or | is bitwise AND/OR.

Anyone with substantial programming knowledge should be able to distinguish the differences.

Although the two may seem to function the same, there are significant variances.

The following are some key distinctions between the & and | operators in Numpy and MATLAB −

• Non-logical inputs of form 0,1: The output of Numpy = bitwise AND of the inputs.

• MATLAB returns the logical AND and treats any value other than 0 as 1. For instance, (3 & 4) in Numpy gives 0, whereas (3 & 4) in MATLAB returns 1 because both 3 and 4 are regarded as logically true.

• MATLAB's & operator has lower precedence than the logical operators like less than (<) and greater than (>); Numpy's precedence is reversed.

Use Numpy's bitwise operators if you are certain that your arguments are booleans, but be cautious when employing parentheses, like in the example below −

z = (x > 1) & (x 2)


An undesirable side effect of Python's design is the lack of logical and, logical or operator forms in NumPy.

### Reshape and linear indexing

MATLAB permits access to multi-dimensional arrays by using linear or scalar indices, whereas Numpy does not.

In MATLAB programs, linear indices are frequently used.

It could be essential to reshape a matrix first into a linear series, carry out some index based operations, and then reshape it again while converting MATLAB code.

Given that reshaping (typically) creates views onto the same storage, this ought to be achieved reasonably quickly. It should be noted that MATLAB utilizes the Fortran order while NumPy defaults to the C order when using the reshape function. This is irrelevant if you are simply changing from a linear series to another one.

### Data Plotting

Lastly, plotting is important when we want to visualise data. Python’s Matplotlib function provides a substantial set of functions to perform plotting operations.

import numpy as np
import matplotlib.pyplot as pltlib
mat = np.matrix([[1,1,1],[2,4,6],[5,7,6]])
pltlib.plot(mat[:,1])
pltlib.plot(mat[:,0])
pltlib.title('MATLAB Plot')
pltlib.xlabel('X-Axis')
pltlib.ylabel('Y-Axis')
pltlib.show()


## Personalizing the Environment

The major option you have in MATLAB for personalizing the workspace is to change the searching path to include the locations of one’s favourite functions. Such modifications can be included in a startup script that will be executed by MATLAB when it starts up.

The facilities in Python are identical to those in NumPy.

Define “PYTHONPATH” environment variable to change Python searching path in order to include the locations of modules.

When starting the interactive Python interpreter, specify a specific script file to run by setting the “PYTHONSTARTUP” environment variable to the name of that file.

In contrast to MATLAB, where anything on the path can be called as per wished, one must first execute an "import" line in Python and make functions in a specific file which is accessible.

## Conclusion

In this tutorial we learnt how MATLAB users can switch to Python and discussed various MATLAB-Python Equivalents.

Updated on: 09-Jan-2023

439 Views