lettura simple

Concatenating Two Matrices in Matlab

In this lesson, I will explain how to concatenate two matrices horizontally or vertically in Matlab.

What does it mean to concatenate two matrices? It means to join the two matrices to create a larger matrix. For example, consider two matrices: $$ A = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix} $$ $$ B = \begin{pmatrix} 5 & 6 \\ 7 & 8 \end{pmatrix} $$ The horizontal concatenation of the two matrices is: $$ A|B = \begin{pmatrix} 1 & 2 & 5 & 6 \\ 3 & 4 & 7 & 8 \end{pmatrix} $$

Here's a practical example.

Create a 2x2 matrix in Matlab and assign it to the variable A.

A=[1 2;3 4]

Now create another 2x2 matrix and assign it to the variable B.

B=[5 6;7 8]

To concatenate the two matrices horizontally, type the command [A,B] or [A B]

>> [A B]
ans =
1 2 5 6
3 4 7 8

Matlab appends the two matrices one after the other.

Alternatively, you can use the function horzcat(A,B)

>> horzcat(A,B)
ans =
1 2 5 6
3 4 7 8

or the command cat(2,A,B)

>> cat(2,A,B)
ans =
1 2 5 6
3 4 7 8

The result is always the same.

Note. You can concatenate two matrices horizontally only if the two matrices have the same number of rows.

To concatenate the two matrices vertically, type the command [A;B]

>> [A;B]
ans =
1 2
3 4
5 6
7 8

In this case, the two matrices A and B are separated by a semicolon, which indicates a line break on the next row.

Matlab appends the rows of the second matrix after the last row of the first matrix.

Alternatively, you can use the function vertcat(A,B)

>> vertcat(A,B)
ans =
1 2
3 4
5 6
7 8

or the command cat(1,A,B)

>> cat(1,A,B)
ans =
1 2
3 4
5 6
7 8

The final result is the same.

Note. You can concatenate two matrices vertically only if they have the same number of columns.

This is how you can concatenate matrices in Matlab, both horizontally and vertically.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin