Vector Indexing in MATLAB
MATLAB is a technical programming environment optimized for operations on matrices and vectors. While programming in the MATLAB environment, you need to access data within a vector, matrix or array -- all equivalent terms -- using different methods. MATLAB implements a broad variety of vector indexing to allow easy subsetting of matrix data with a minimal amount of coding.
-
Single Elements
-
Single elements of MATLAB vectors are accessed using a numerical index. MATLAB begins the index of a vector dimension at 1, where other languages begin at 0. The indexes of different dimensions are separated by a comma. A MATLAB integer variable may also be used as an index as in the following example.
my_vector(1, 7, my_index_integer);
Lists
-
Multiple vector elements can be accessed by using a vector as an index, using the same syntax as single element indexing. A MATLAB one-dimensional vector variable can be used or a new vector can be created de novo by enclosing a comma-separated list of numbers enclosed in brackets as in the following example.
my_vector([1, 5, 9], my_vector_index);
Ranges
-
Continuous ranges of vector elements can be accessed using the colon operator to define a range. A range must have a start and stop index separated by a colon. An increment can also be included. For vector indexing, all values defined by a range must be integers as demonstrated here.
my_vector(1:10);
my_vector(1:5:101);
Logical Indexing
-
MATLAB also allows the use of logical or Boolean arrays to access elements of an array. Logical arrays have a value of true or false, represented by 1 or 0. However, any numerical array can be treated as a logical array, with any nonzero value being considered true. The returned value is a one-dimensional vector containing all elements corresponding to a true index, regardless of the vector dimensions. The find() function with the same logical array as an input will return the indices of the true value for interpreting the results of logical indexing.
my_values = my_vector([0, 1, 1, 0, 0, 1]);
my_values = my_vector(my_logical_array);my_indices = find([0, 1, 1, 0, 0, 1]);
-
Related Searches
References
- Photo Credit Thinkstock Images/Comstock/Getty Images