0
0
MATLABdata~5 mins

Matrix concatenation in MATLAB

Choose your learning style9 modes available
Introduction

Matrix concatenation lets you join two or more matrices side by side or one after another. It helps combine data easily.

You want to join two tables of numbers horizontally to compare columns.
You have separate data sets and want to stack them vertically to analyze together.
You want to build a bigger matrix from smaller pieces step by step.
You need to add new rows or columns to an existing matrix.
You want to merge results from different calculations into one matrix.
Syntax
MATLAB
C = [A, B];  % Horizontal concatenation
C = [A; B];  % Vertical concatenation

Use commas or spaces inside square brackets to join matrices side by side (columns).

Use semicolons inside square brackets to join matrices one below another (rows).

Examples
This joins A and B side by side, making a matrix with 2 rows and 4 columns.
MATLAB
A = [1 2; 3 4];
B = [5 6; 7 8];
C = [A, B];
This stacks A on top of B, making a matrix with 4 rows and 2 columns.
MATLAB
A = [1 2; 3 4];
B = [5 6; 7 8];
C = [A; B];
Joining two row vectors vertically to make a 2-row matrix.
MATLAB
A = [1 2 3];
B = [4 5 6];
C = [A; B];
Sample Program

This program creates two 2x2 matrices A and B. Then it joins them side by side into C and one below another into D. It prints both results.

MATLAB
A = [10 20; 30 40];
B = [50 60; 70 80];

% Horizontal concatenation
C = [A, B];

% Vertical concatenation
D = [A; B];

fprintf('Matrix C (horizontal concatenation):\n');
disp(C);

fprintf('Matrix D (vertical concatenation):\n');
disp(D);
OutputSuccess
Important Notes

Make sure the dimensions match when concatenating. For horizontal, rows must be equal. For vertical, columns must be equal.

If dimensions don't match, MATLAB will give an error.

You can concatenate more than two matrices by adding more inside the brackets.

Summary

Matrix concatenation joins matrices horizontally with commas or spaces.

Use semicolons to join matrices vertically.

Dimensions must match properly to avoid errors.