0

I met a problem.

I drew this figure below

enter image description here

with a MATLAB/Octave code

t=[0,0.01,0.98]
y2=cos(8*pi*t);
plot(t,y2);

I tried to write it to Python code, but failed. I have something clue of python code as below

def drange(begin, end, step):
    n = begin
    while n+step < end:
     yield n
     n += step
9
  • @sacul Indeed, it's very similar to Python code. In fact, 0 means begin, 0.01 means step, 0.98 means end in MATLAB/Octave code. Commented Jul 21, 2018 at 14:54
  • 1
    please, write your try. Thank you Commented Jul 21, 2018 at 14:55
  • As far as I know, what you posted in both matlab AND python is a vector / list of floats. If you're looking for a range from 0 to 0.98 in python, you'll have to use numpy: import numpy as np followed by t=np.arange(0,0.98,0.01) Commented Jul 21, 2018 at 15:02
  • Also, please provide some more code as context. This code is valid python, but based on your description it seems to be used to do something else. But it isn't clear without code what that "something else" is. Commented Jul 21, 2018 at 15:02
  • 1
    @sacul: MATLAB ranges include the end while numpy ones don't. So it would need to be np.arange(0, 0.99, 0.01) Commented Jul 21, 2018 at 15:03

1 Answer 1

3

Your MATLAB code does not create the plot you showed. This is because t is not a range, but a vector of the 3 values 0, 0.01 and 0.098, so instead, it plots only those 3 points:

enter image description here

Fixing your MATLAB code

To create the plot you showed in MATLAB, you can do this:

t=[0:0.01:0.98];
y2=cos(8*pi*t);
plot(t,y2);

Notice the use of the : instead of the ,, to specify that you want a range of values from 0 to 0.98 with a step of 0.01, rather than the vector of the three values 0, 0.01 and 0.98.

Recreating the plot in python:

use np.arange, as well as the cos and pi functions provided by numpy

import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0,0.99,0.01)
y = np.cos(8*np.pi*t)
plt.plot(t, y)
plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Given that 0.98 and 0.99 are inexact and the rounding may be off, I would use something like 0.985 as the limit to ensure the correct number of points. Alternatively, you can use np.linspace(0.0, 0.98, 99)
Those are just nitpicks. Excellent answer. Good job addressing all of OP's issues.

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.