10

range()Python中的函数是否有等效的MATLAB函数?

我真的很希望能够输入类似的内容range(-10, 11, 5)并返回[-10, -5, 0, 5, 10],而不必手动写出整个范围。

4

3 回答 3

15

是的,有:运营商。该命令-10:5:11将产生向量[-10, -5, 0, 5, 10];

于 2012-08-09T19:19:56.593 回答
7

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. (e.g. x = -10:5:11).

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

于 2012-08-09T19:40:28.293 回答
3

其他人提到了colon运营商。你只需要意识到一些差异。

在 Python 中,range接受所有整数参数并返回一个整数列表。在 MATLAB 中,冒号运算符可以处理开始/停止以及步长中的浮点数。

我会说这numpy.arange与 MATLAB 的冒号运算符更匹配。

于 2012-08-09T23:16:31.333 回答