askvity

How do you combine multiple arrays in MATLAB?

Published in MATLAB array concatenation 3 mins read

In MATLAB, you can combine multiple arrays primarily by using the square bracket operator [].

Combining arrays, also known as concatenation, allows you to merge the elements of different arrays into a single, larger array. This is a fundamental operation in MATLAB for building matrices and vectors from smaller components. The method you use depends on whether you want to combine arrays side-by-side (horizontally) or one below the other (vertically).

Using the Square Bracket Operator []

The most common and straightforward way to combine arrays in MATLAB is by enclosing them within square brackets []. MATLAB interprets the arrangement of arrays inside the brackets to determine how they should be combined.

Horizontal Concatenation

To combine arrays side-by-side (horizontally), you place them next to each other within the square brackets. You can use either a comma , or a space to separate the arrays.

  • Syntax:

    • [Array1, Array2, Array3, ...]
    • [Array1 Array2 Array3 ...]
  • Requirement: The arrays being concatenated horizontally must have the same number of rows.

  • Example:
    Let's say you have two row vectors or matrices with the same number of rows:

    A = [1, 2, 3];
    B = [4, 5, 6];
    % Combine horizontally using a comma
    C = [A, B];
    % C is now [1, 2, 3, 4, 5, 6]
    
    D = [7, 8; 9, 10];
    E = [11, 12; 13, 14];
    % Combine horizontally using a space
    F = [D E];
    % F is now [7, 8, 11, 12; 9, 10, 13, 14]

    As stated in the reference, [A,B] and [A B] both concatenate arrays A and B horizontally.

Vertical Concatenation

To combine arrays one above the other (vertically), you use a semicolon ; to separate the arrays within the square brackets.

  • Syntax:

    • [Array1; Array2; Array3; ...]
  • Requirement: The arrays being concatenated vertically must have the same number of columns.

  • Example:
    Let's say you have two column vectors or matrices with the same number of columns:

    A = [1; 2; 3];
    B = [4; 5; 6];
    % Combine vertically
    C = [A; B];
    % C is now [1; 2; 3; 4; 5; 6]
    
    D = [7, 8; 9, 10];
    E = [11, 12; 13, 14];
    % Combine vertically
    F = [D; E];
    % F is now [7, 8; 9, 10; 11, 12; 13, 14]

    As stated in the reference, [A; B] concatenates arrays A and B vertically.

Combining Multiple Dimensions

For arrays with more than two dimensions (like 3D arrays), you can use cat(dim, A, B, ...) where dim is the dimension along which you want to concatenate. However, based only on the provided reference, the primary method discussed is the use of the [] operator for horizontal and vertical concatenation.

The square bracket operator [] is the fundamental tool in MATLAB for efficiently combining arrays of various types and sizes, provided the dimensions align correctly for the chosen concatenation direction.

Related Articles