How do I make an array that's defined with a start point, an end point, and a total array size? Something like an array that goes from 1 to 10 that's 20 elements long. For example, the array could look something like:
如何创建一个具有起点、终点和总数组大小的数组?比如一个从1到10的数组也就是20个元素长。例如,数组可以如下所示:
1 1.5 2 2.5 3 3.5 ...
3 个解决方案
#1
18
There are a couple of ways you can do this:
有几种方法可以做到这一点:
-
Using the colon operator:
使用冒号运算符:
startValue = 1; endValue = 10; nElements = 20; stepSize = (endValue-startValue)/(nElements-1); A = startValue:stepSize:endValue;
-
Using the
linspace
function (as suggested by Amro):使用linspace函数(如银行所建议的):
startValue = 1; endValue = 10; nElements = 20; A = linspace(startValue,endValue,nElements);
Keep in mind that the number of elements in the resulting arrays includes the end points. In the above examples, the difference between array element values will be 9/19
, or a little less than 0.5
(unlike the sample array in the question).
记住,结果数组中的元素数量包括端点。在上面的示例中,数组元素值之间的差异将是9/19,或略小于0.5(与问题中的示例数组不同)。
#2
10
linspace generates linearly spaced vectors:
linspace生成线性间隔向量:
>> A = linspace(1, 10, 20-1)
ans =
1 1.5 2 2.5 3 3.5 ... 9.5 10
#3
5
Simple one-liner!
简单的一行程序!
1:0.5:10;
Output:
输出:
1 1.5 2 2.5 ... 9 9.5 10
Note that this would be a 19-element vector, not 20.
注意这是一个19元向量,而不是20。
#1
18
There are a couple of ways you can do this:
有几种方法可以做到这一点:
-
Using the colon operator:
使用冒号运算符:
startValue = 1; endValue = 10; nElements = 20; stepSize = (endValue-startValue)/(nElements-1); A = startValue:stepSize:endValue;
-
Using the
linspace
function (as suggested by Amro):使用linspace函数(如银行所建议的):
startValue = 1; endValue = 10; nElements = 20; A = linspace(startValue,endValue,nElements);
Keep in mind that the number of elements in the resulting arrays includes the end points. In the above examples, the difference between array element values will be 9/19
, or a little less than 0.5
(unlike the sample array in the question).
记住,结果数组中的元素数量包括端点。在上面的示例中,数组元素值之间的差异将是9/19,或略小于0.5(与问题中的示例数组不同)。
#2
10
linspace generates linearly spaced vectors:
linspace生成线性间隔向量:
>> A = linspace(1, 10, 20-1)
ans =
1 1.5 2 2.5 3 3.5 ... 9.5 10
#3
5
Simple one-liner!
简单的一行程序!
1:0.5:10;
Output:
输出:
1 1.5 2 2.5 ... 9 9.5 10
Note that this would be a 19-element vector, not 20.
注意这是一个19元向量,而不是20。