简体   繁体   中英

Is there an equivalent of the Python range function in MATLAB?

Is there an equivalent MATLAB function for the range() function in Python?

I'd really like to be able to type something like range(-10, 11, 5) and get back [-10, -5, 0, 5, 10] instead of having to write out the entire range by hand.

Yes, there is the : operator. The command -10:5:11 would produce the vector [-10, -5, 0, 5, 10];

There are two relevant functions. The colon : operator, you can use the linspace function. The best function to use depends on what you want to specify.

Examples:

x = -10:5:10;              % Count by 5's from -10 to 10.  (or "colon(-10, 5, 10)")
x = linspace(-10, 10, 5);  % 5 even increments between -10 and 10

The result of the colon operator will always include the first argument and the desired spacing, but generally will not include the last argument. (eg x = -10:5:11 ).

The linspace function will always include the desired first and last elements, but will the element spacing will vary. (eg linspace(-10, 11, 5) ).

Others have mentioned the colon operator. You just have to be aware of some differences.

In Python, range takes all integer parameters and returns an integer list. In MATLAB, the colon operator can handle floating point in both the start/stop as well as the step size.

I would say that numpy.arange is a closer match to MATLAB's colon operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM