Row vectors
In MATLAB you can create a row vector using square brackets [ ]. Elements of the vector may be separated either by one or more blanks or a comma ,.
Square brackets are use to create a row vector.
The elements may be separated either by blanks or commas.
The elements of a vector may be the result of arithmetic operations.
Square brackets are use to create a row vector, whose elements may be MATLAB expressions.
The elements may be separated by commas or blank spaces.
Elements of vectors
To refer to elements in a vector MATLAB uses round brackets ( ). For example, the second element x2, is referenced by x(2). This can be used either to get the value of an element or to assign a value to an element of a vector.
y(2) displays the value of the second element of the vector stored in the variable y .
This assigns the value -1 to the second element of y.
Note that the whole vector y is echoed to the command window, even though only the second element was changed.
Accessing several elements of a vector
The elements of a vector are indexed, starting with 1 continuing to the length of the vector, just as in mathematics.
MATLAB uses vectors of integers between 1 and the length of a vector to refer to several elements of a vector at once. For example x([2 3]) refers to the second and third elements x2, x3 of x.
This displays elements 1 and 3 of the vector x, assuming x has already been defined. Note that there is a blank between the 1 and the 3, so it is not x([13]).
Although a space is commonly used to separate elements, to make it clearer a comma can be used to separate the 1 and the 3.
i2 is a vector with elements 1, 3, 2, 1
This produces a vector consisting of the elements of x corresponding to the values in i2 and assigns the result to a variable called sample1.
Number of elements in a vector
The number of elements in an array (for instance a vector) can be found using the MATLAB command numel.
The vector has four elements.
The length of a vector can also be found using the MATLAB command length. For vectors this is the same as numel.
The vector has four elements.
Warnings
- For large vectors it is important to use a semi-colon at the end of a command to suppress output.
- For matrices and multi-dimensional arrays it is better to use the size or numel commands rather than the length command.
- For multi-dimensional arrays, length gives the maximum of size.
Self-test Exercise
Create a vector u with elements k2, k = 6,...,12, then create a vector v consisting of elements 1, 3, 5, 7 of u. Check that v has length 4.Answer:
- u = [6^2 7^2 8^2 9^2 10^2 11^2 12^2]
- v = u([1 3 5 7])
- numel(v)
We will see a much easier way to construct u and v after the next two modules!
Summary
Row vectors are created using square brackets [ ], with blank spaces or commas to separate elements.
Element k of a vector u is accessed as u(k), where k is an integer between 1 and numel(u).