Table of Contents

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])

Another example is if I want the first 3 elements of the vector. I could refer to these like this ...

V([1 2 3])

Or equally, using colon notation, like this

V(1:3)

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.

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]

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)

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)

Another way of saying the same thing is like this

[V1; V2]

or

[V1;

V2]

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)

Vertical concatenation is concatenating along the first dimension (because it makes more rows, which come first by convention)

cat(1, V1, V2)

Concatenating in the third dimension makes a tensor

cat(3, V1, V2)

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)

Note that you can also concatenate matrices horizontally and vertically ...

[M1 M2]

[M1; M2]