0

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

1
  • 1
    Have you tried reading the documentation for eps and :? Commented Mar 3, 2017 at 20:07

1 Answer 1

4

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,)
Sign up to request clarification or add additional context in comments.

3 Comments

So...what does it do?
the semantics of arange doesn't include the endpoint; beware. In other words, 1:2:5 in MATLAB is NOT the same as np.arange(1,5,2)
@JasonS true, fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.