# How to concatenate vectors in Matlab and Octave

To concatenate and join two or more row vectors in Matlab and Octave write

v = [v1 v2]

If v1 and v2 are two column vectors, write

v = [v1; v2]

In both cases the result is a vector v with all the elements of the vectors v1 and v2.

Note. The elements of the second vector v2 are added at the end of the elements of the first vector v1.

## Examples

Example 1

Create a row vector v1

>> v1=[1 2 3]
v1 =
1 2 3

Create another row vector v2

>> v2=[4 5 6 7]
v2 =
4 5 6 7

To concatenate the two vectors, type

>> v=[v1 v2]

The output result is a vector with all the elements of v1 and v2

v =
1 2 3 4 5 6 7

Example 2

Create a column vector

>> v1=[1; 2; 3]
v1 =
1
2
3

Create another column vector v2

>> v2=[4; 5; 6; 7]
v2 =
4
5
6
7

To concatenate two column vectors write

>> v=[v1;v2]
v =
1
2
3
4
5
6
7

Example 3

Create a column vector

>> v1=[1; 2; 3]
v1 =
1
2
3

Create another column vector v2

>> v2=[4; 5; 6; 7]
v2 =
4
5
6
7

Alternatively, to concatenate the two column vectors, it is also possible to transform them into row vectors by transposing

>> v=[v1' v2']
v =
1 2 3 4 5 6 7

The result is a row vector v with the elements of v1 and v2.

Finally, transform the row vector v into a column vector with another transposition.

>> v=v'
v =
1
2
3
4
5
6
7

The end result is the same.

Esempio 4

Create a column vector v1

>> v1=[1; 2; 3]
v1 =
1
2
3

Create a row vector v2

>> v2=[4 5 6 7]
v2 =
4 5 6 7

To concatenate the two vectors in a column vector, the first vector must be concatenated with the transposition of the second vector.

>> v=[v1 ; v2']
v =
1
2
3
4
5
6
7

To concatenate the two vectors in a row vector, we need to concatenate the transposition of the first vector with the second vector.

>> v=[v1' v2]
v=
1 2 3 4 5 6 7

https://how.okpedia.org/en/matlab/how-to-concatenate-vectors-in-matlab-and-octave Report us an error or send a suggestion to improve this page