MATLAB - Appending Vectors



MATLAB allows you to append vectors together to create new vectors.

If you have two row vectors r1 and r2 with n and m number of elements, to create a row vector r of n plus m elements, by appending these vectors, you write −

r = [r1,r2]

You can also create a matrix r by appending these two vectors, the vector r2, will be the second row of the matrix −

r = [r1;r2]

However, to do this, both the vectors should have same number of elements.

Similarly, you can append two column vectors c1 and c2 with n and m number of elements. To create a column vector c of n plus m elements, by appending these vectors, you write −

c = [c1; c2]

You can also create a matrix c by appending these two vectors; the vector c2 will be the second column of the matrix −

c = [c1, c2]

However, to do this, both the vectors should have same number of elements.

Example

Create a script file with the following code −

r1 = [ 1 2 3 4 ];
r2 = [5 6 7 8 ];
r = [r1,r2]
rMat = [r1;r2]
 
c1 = [ 1; 2; 3; 4 ];
c2 = [5; 6; 7; 8 ];
c = [c1; c2]
cMat = [c1,c2]

When you run the file, it displays the following result −

r =

Columns 1 through 7:

         1          2          3          4          5          6          7

Column 8:

         8

rMat =

         1          2          3          4
         5          6          7          8

c =

         1
         2
         3
         4
         5
         6
         7
         8

cMat =

         1          5
         2          6
         3          7
         4          8

matlab_vectors.htm
Advertisements