lettura simple

How to concatenate matrices in Octave

In this lesson I'll explain how to join two matrices horizontally or vertically in Octave.

What does it mean to concatenate two matrices? t is an operation that joins the rows or columns of two matrices creating a larger matrix. For example, you have two matrices $$ A = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix} $$ $$ B = \begin{pmatrix} 5 & 6 \\ 7 & 8 \end{pmatrix} $$ Horizontally concatenating matrices is to add the columns of the second matrix to the end of the first matrix $$ A|B = \begin{pmatrix} 1 & 2 & 5 & 6 \\ 3 & 4 & 7 & 8 \end{pmatrix} $$

I'll give you a practical example

Define a square matrix in variable A

A=[1 2;3 4]

Then define a square matrix in variable B.

B=[5 6;7 8]

Now concatenate the two matrices horizontally by typing the command [A, B] or [A B]

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

Octave adds the columns of the second matrix after the last column of the first matrix.

$$ A|B = \begin{pmatrix} 1 & 2 & 5 & 6 \\ 3 & 4 & 7 & 8 \end{pmatrix} $$

Alternatively, you can also type horzcat(A,B) function

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

or type cat(2,A,B) function

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

The final outcome is the same.

Note. You can aggregate two arrays horizontally only if the two arrays have the same number of rows. The number of columns can also be different.

Now concatenate the two matrices vertically by typing [A;B]

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

The semicolon symbol is equivalent to a carriage return on the next line.

In this case Octave aggregates the rows of the second matrix after the last row of the first matrix.

$$ A|B = \begin{pmatrix} 1 & 2 \\ 3 & 4 \\ 5 & 6 \\ 7 & 8 \end{pmatrix} $$

Alternatively, you can get the same result using vertcat(A,B) function

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

or cat(1,A,B) function

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

The result is the same.

Note. You can aggregate two arrays vertically only if they have the same number of columns. The number of lines can also be different.

This way you can concatenate two matrices both vertically and horizontally in Octave.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin