Programming

Concatenating Matrices

Matrix concatenation is the process of joining one or more matrices to make a new matrix. The brackets [] operator discussed earlier in this section serves not only as a matrix constructor, but also as the MATLAB concatenation operator. The expression C = [A B] horizontally concatenates matrices A and B. The expression C = [A; B] vertically concatenates them.

This example constructs a new matrix C by concatenating matrices A and B in a vertical direction:

• A = ones(2, 5) * 6;        % 2-by-5 matrix of 6's
B = rand(3, 5);            % 3-by-5 matrix of random values

C = [A; B]                 % Vertically concatenate A and B
C =
6.0000    6.0000    6.0000    6.0000    6.0000
6.0000    6.0000    6.0000    6.0000    6.0000
0.6154    0.7382    0.9355    0.8936    0.8132
0.7919    0.1763    0.9169    0.0579    0.0099
0.9218    0.4057    0.4103    0.3529    0.1389

Keeping Matrices Rectangular

You can construct matrices, or even multidimensional arrays, using concatenation as long as the resulting matrix does not have an irregular shape (as in the second illustration shown below). If you are building a matrix horizontally, then each component matrix must have the same number of rows. When building vertically, each component must have the same number of columns.

This diagram shows two matrices of the same height (i.e., same number of rows) being combined horizontally to form a new matrix.

The next diagram illustrates an attempt to horizontally combine two matrices of unequal height. MATLAB does not allow this.

 Specialized Matrix Functions Matrix Concatenation Functions

© 1994-2005 The MathWorks, Inc.