简体   繁体   English

在MATLAB中是否有相当于Python范围的功能?

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

Is there an equivalent MATLAB function for the range() function in Python? Python中的range()函数是否有等效的MATLAB函数?

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. 我真的希望能够键入range(-10, 11, 5)并返回[-10, -5, 0, 5, 10]而不必手动写出整个范围。

Yes, there is the : operator. 是的,有:运营商。 The command -10:5:11 would produce the vector [-10, -5, 0, 5, 10]; 命令-10:5:11将产生向量[-10, -5, 0, 5, 10];

There are two relevant functions. 有两个相关的功能。 The colon : operator, you can use the linspace function. 冒号:运算符,可以使用linspace函数。 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. colon运算符的结果将始终包含第一个参数和所需的间距,但通常不包括最后一个参数。 (eg x = -10:5:11 ). (例如x = -10:5:11 )。

The linspace function will always include the desired first and last elements, but will the element spacing will vary. linspace函数将始终包含所需的第一个和最后一个元素,但元素间距将会变化。 (eg linspace(-10, 11, 5) ). (例如linspace(-10, 11, 5) )。

Others have mentioned the colon operator. 其他人提到了colon操作员。 You just have to be aware of some differences. 你只需要意识到一些差异。

In Python, range takes all integer parameters and returns an integer list. 在Python中, range获取所有整数参数并返回整数列表。 In MATLAB, the colon operator can handle floating point in both the start/stop as well as the step size. 在MATLAB中,冒号运算符可以处理启动/停止以及步长的浮点。

I would say that numpy.arange is a closer match to MATLAB's colon operator. 我会说numpy.arange与MATLAB的冒号运算符更接近。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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