NSCS 344, Week 4: Matlab Concepts

Table of Contents

Indexing several elements of a vector

Sometimes we would like to get several elements of a vector or matrix at once. For example, if I have the vector
V = [8 84 21 3 0];
I might want the 2nd and 4th element for some reason. To do this I can us a vector as an index to the vector, like this
V([2 4])
ans = 1×2
84 3
Another example is if I want the first 3 elements of the vector. I could refer to these like this ...
V([1 2 3])
ans = 1×3
8 84 21
Or equally, using colon notation, like this
V(1:3)
ans = 1×3
8 84 21
This latter notation makes things really easy if I have lots of elements in my vector and want to refer to (say) a subset of 100 of them.

Concatenating vectors

Sometimes I would like to stick two vectors together end-to-end. For example
V1 = [1 2 3];
V2 = [4 5 6];
I could stick them together like this ....
V = [V1 V2]
V = 1×6
1 2 3 4 5 6
This is called horizontal concatenation, because we are concatentating the vectors in the horizonatal direction. Another way to do this is with the horzcat function
V = horzcat(V1, V2)
V = 1×6
1 2 3 4 5 6
But, this isn't the only way I could stick these two vectors together. Instead of concatenating them end-to-end, I could stick one vector on top of the other to make a matrix. That is I could concatenate them vertically
vertcat(V1, V2)
ans = 2×3
1 2 3 4 5 6
Another way of saying the same thing is like this
[V1; V2]
ans = 2×3
1 2 3 4 5 6
or
[V1;
V2]
ans = 2×3
1 2 3 4 5 6
Finally, if I want to concatenate along a generate dimension, I can use the cat function. For example, horizontal concatenation is concatenating along the second dimension (because it makes more columns, which come second by convention)
cat(2, V1, V2)
ans = 1×6
1 2 3 4 5 6
Vertical concatenation is concatenating along the first dimension (because it makes more rows, which come first by convention)
cat(1, V1, V2)
ans = 2×3
1 2 3 4 5 6
Concatenating in the third dimension makes a tensor
cat(3, V1, V2)
ans =
ans(:,:,1) = 1 2 3 ans(:,:,2) = 4 5 6
Although you'd be unlikely to do this with vectors. Instead you're more likely to concatenate matrices in the 3rd dimension ...
M1 = [1 2 3;
4 5 6];
M2 = [8 9 10;
11 12 13];
cat(3, M1, M2)
ans =
ans(:,:,1) = 1 2 3 4 5 6 ans(:,:,2) = 8 9 10 11 12 13
Note that you can also concatenate matrices horizontally and vertically ...
[M1 M2]
ans = 2×6
1 2 3 8 9 10 4 5 6 11 12 13
[M1; M2]
ans = 4×3
1 2 3 4 5 6 8 9 10 11 12 13