views:

121

answers:

3

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 1.5 2 2.5 3 3.5 ...
+7  A: 

linspace generates linearly spaced vectors:

>>  A = linspace(1, 10, 20-1)
ans =
1 1.5 2 2.5 3 3.5 ... 9.5 10
Amro
n.b. `linspace` outputs *row* vectors; here in optimization land, all vectors are column vectors. beware.
shabbychef
the OP want to create an array with 20 elements and you're talking about some negligible optimization (which may not even be the case!!)
Amro
+3  A: 

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):

    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).

gnovice
+2  A: 

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.

Zaid
No, this would be a *19-element* vector. It would include the integers 1 to 10 (of which there are 10), along with the midpoints between each pair of integers (of which there are 9).
gnovice
@gnovice: Thanks for the heads up.
Zaid