0
0
MatlabHow-ToBeginner ยท 3 min read

How to Concatenate Matrices in MATLAB: Syntax and Examples

In MATLAB, you concatenate matrices using square brackets []. Use [A, B] to join matrices horizontally (side by side) and [A; B] to join them vertically (one on top of the other).
๐Ÿ“

Syntax

To concatenate matrices in MATLAB, use square brackets []. Horizontal concatenation places matrices side by side, separated by commas or spaces. Vertical concatenation stacks matrices on top of each other, separated by semicolons.

  • Horizontal: [A, B] or [A B]
  • Vertical: [A; B]

Both matrices must have compatible sizes: for horizontal concatenation, they must have the same number of rows; for vertical, the same number of columns.

matlab
[A, B]  % Horizontal concatenation
[A; B]  % Vertical concatenation
๐Ÿ’ป

Example

This example shows how to concatenate two matrices horizontally and vertically. It demonstrates the syntax and the resulting matrices.

matlab
A = [1 2 3; 4 5 6];
B = [7 8 9; 10 11 12];

% Horizontal concatenation
H = [A, B];

% Vertical concatenation
V = [A; B];

H
V
Output
H = 1 2 3 7 8 9 4 5 6 10 11 12 V = 1 2 3 4 5 6 7 8 9 10 11 12
โš ๏ธ

Common Pitfalls

Common mistakes when concatenating matrices include:

  • Trying to concatenate matrices with incompatible sizes (different row counts for horizontal, or different column counts for vertical).
  • Using commas instead of semicolons for vertical concatenation or vice versa.
  • Confusing horizontal and vertical concatenation syntax.

Always check matrix dimensions before concatenation.

matlab
% Wrong: different row counts for horizontal concatenation
A = [1 2; 3 4];
B = [5 6 7];
% This will cause an error:
% C = [A, B];

% Correct approach: adjust sizes or use vertical concatenation if columns match
B = [5 6];
C = [A; B];  % Works if columns match
๐Ÿ“Š

Quick Reference

Summary of matrix concatenation in MATLAB:

OperationSyntaxRequirement
Horizontal Concatenation[A, B] or [A B]Same number of rows
Vertical Concatenation[A; B]Same number of columns
โœ…

Key Takeaways

Use square brackets [] to concatenate matrices in MATLAB.
Use commas or spaces for horizontal concatenation; use semicolons for vertical concatenation.
Ensure matrices have compatible dimensions before concatenating.
Horizontal concatenation requires matching row counts; vertical requires matching column counts.
Check matrix sizes to avoid dimension mismatch errors.