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 ...
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 .
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 .
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.
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.
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).
linspace generates linearly spaced vectors:
>> A = linspace(1, 10, 20-1)
ans =
1 1.5 2 2.5 3 3.5 ... 9.5 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With