how to concatenate multiple vectors into one matrix in matlab

To concatenate multiple vectors into one matrix in MATLAB, we can use the horzcat or vertcat functions.

Assume you have three row vectors a, b, and c:

main.m
a = [1 2 3]; 
b = [4 5 6]; 
c = [7 8 9];
41 chars
4 lines

To concatenate these vectors horizontally (i.e., add them as new columns), we use the horzcat function:

main.m
matrix = horzcat(a', b', c') % put vectors as columns in matrix
64 chars
2 lines

To concatenate them vertically (i.e., add them as new rows), we use vertcat function:

main.m
matrix = vertcat(a', b', c') % put vectors as rows in matrix
61 chars
2 lines

Note that the vectors must have the same size in the dimension of concatenation. In the above example, the vectors have size 1x3, so they can be combined either horizontally or vertically.

The resulting matrix will be:

main.m
matrix =

     1     4     7
     2     5     8
     3     6     9
67 chars
6 lines

where the vectors are added as three columns of the matrix.

related categories

gistlibby LogSnag