Newtt
Newtt

Reputation: 6190

Python equivalent for given MATLAB code

I'm trying to rewrite a certain snippet of MATLAB for python as I'm not too comfortable using MATLAB.

a = 0.5 
b = 50
ph = (eps:a:b) 

This is what I'm trying to convert to Python but the problem is I don't really know what the last line does. Hence I'm not able to proceed

Upvotes: 0

Views: 395

Answers (1)

NKN
NKN

Reputation: 6424

In MATLAB you are making a range of numbers from say 0 to 50 by 0.5 step. It can be done like this: ph=0:0.5:50;

For some reason (maybe having dividing by zero) you replace the 0 in the range with the smallest machine number eps, in MATLAB.

eps =

     2.220446049250313e-16

The equivalent in python can be the use of the arange function to make a range of numbers with a specific step (arange doc). If you import numpy it can be something like this:

import numpy as np
np.arange(np.finfo(float).eps,50,0.5)

However, as mentioned in the comments, to include the endpoint, one way is to add one step to the range manually.

np.arange(np.finfo(float).eps,50+0.5,0.5)

By doing this, the endpoint would be 50.5 and the range will stop at 50 as you want.

Another alternative is to use linspace as follows:

np.linspace(np.finfo(float).eps, 50, 50/0.5+1, endpoint=True)

Here you can provide the endpoint to be included in the range. The disadvantage is that you need to define the number of elements instead of the stepsize (linspace doc).

Both vectors should have the same size, you can check that:

np.shape(np.linspace(np.finfo(float).eps, 50, 50/0.5+1, endpoint=True))
(101,)
np.shape(np.arange(np.finfo(float).eps,50+0.5,0.5))
(101,)

Upvotes: 4

Related Questions