Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a regularly-spaced array of values in MATLAB?

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 ...
like image 526
bobber205 Avatar asked Dec 05 '09 23:12

bobber205


People also ask

How do you create an array of values in MATLAB?

To create an array with four elements in a single row, separate the elements with either a comma ( , ) or a space. This type of array is a row vector. To create a matrix that has multiple rows, separate the rows with semicolons. Another way to create a matrix is to use a function, such as ones , zeros , or rand .

How do you create a range of values in MATLAB?

y = range( X , dim ) returns the range along the operating dimension dim of X . For example, if X is a matrix, then range(X,2) is a column vector containing the range value of each row. y = range( X , vecdim ) returns the range over the dimensions specified in the vector vecdim .

What is a MATLAB function to generate linearly spaced vectors?

The linspace function generates linearly spaced vectors. It is similar to the colon operator ":", but gives direct control over the number of points. y = linspace(a,b) generates a row vector y of 100 points linearly spaced between and including a and b.

How do I create an array of all ones in MATLAB?

X = ones( sz ) returns an array of ones where the size vector, sz , defines size(X) . For example, ones([2,3]) returns a 2-by-3 array of ones. X = ones(___, typename ) also specifies the data type (class) of X for any of the previous syntaxes. For example, ones(5,'int8') returns a 5-by-5 matrix of 8-bit integers.


2 Answers

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

like image 180
gnovice Avatar answered Nov 01 '22 12:11

gnovice


linspace generates linearly spaced vectors:

>>  A = linspace(1, 10, 20-1)
ans =
1 1.5 2 2.5 3 3.5 ... 9.5 10
like image 35
Amro Avatar answered Nov 01 '22 11:11

Amro