NSCS 344, Week 4: Matlab Concepts
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
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
Another example is if I want the first 3 elements of the vector. I could refer to these like this ...
Or equally, using colon notation, like this
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
I could stick them together like this ....
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
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
Another way of saying the same thing is like this
or
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)
Vertical concatenation is concatenating along the first dimension (because it makes more rows, which come first by convention)
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 ...
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]
1 2 3 8 9 10
4 5 6 11 12 13
[M1; M2]
1 2 3
4 5 6
8 9 10
11 12 13