Vectors: Vector calculus in MATLAB
Selection of components, and assignment of values
Selection of components and subvectors You can select components of vectors in different ways. We give a few examples showing that indexing starts at 1 and that there a smart methods to create some vectors.
>> v = 6:10
v = 6 7 8 9 10
>> v(2) % a single component
ans = 7
>> v([2,4]) % several components
ans = 7 9
>> v(2:4) % a subvector
ans = 7 8 9
>> v(2:end) % everything except the first component
ans = 7 8 9 10
>> v(1:end-1) % everything except the last component
ans = 6 7 8 9
>> v(:) % everything as column vector
ans =
6
7
8
9
10
Selection via logical expressions You can also use logical indexing (with values zero and one) to select components of vectors. You need relational operators for this, such as the ones in the table below. Besides logical indexing you can also use the find
instruction to find suitable indices for a logical expression.
== | equal to | ~= | not equal to |
< | less than | > | greater than |
<= | less than or equal to | >= | greater than or equal to |
>> v = 5:10
v = 5 6 7 8 9 10
>> v>8 % vector values 1 if the condition is met and otherwise 0
ans = 1×6 logical array 0 0 0 0 1 1
>> v(ans) % selection of components
ans = 9 10
>> find(v<8) % selection of indices via find command
ans = 1 2 3
>> v(ans) % selection of components
ans = 5 6 7
Assignment Components to which you refer can also be assigned new values.
>> v = 5:10; v(1)=4; v % assign the first component the value 4 v = 4 6 7 8 9 10 >> v(1:2) = 5 % assign the first two components the value 5 v = 5 5 7 8 9 10 >> v(2) = [] % remove the second component v = 5 7 8 9 10 >> v(:) = 1 % assign all components the value 1 v = 1 1 1 1 1
By assignments you cannot change the structure. In the example below, we give the vector is an extra component via the append
function, but this is not done in-line, that is to say, the structure of the vector does not change (an assignment is required for this purpose). By the way, this is not a recommended approach. Pre-reserving ample space for components in a vector using the zero construction and then filling the data vector with values by assignments is a better way to collect data in MATLAB experiments such as response times to stimuli.
>> clear all
>> v = 5:7; % vector of length 3
>> v(4)= 8 % new component
v = 5 6 7 8