Programming |

**Matrix Concatenation Functions**

The following functions combine existing matrices to form a new matrix.

Function |
Description |

`cat` |
Concatenate matrices along the specified dimension |

`horzcat` |
Horizontally concatenate matrices |

`vertcat` |
Vertically concatenate matrices |

`repmat` |
Create a new matrix by replicating and tiling existing matrices |

`blkdiag` |
Create a block diagonal matrix from existing matrices |

**Examples**

Here are some examples of how you can use these functions.

**Concatenating Matrices and Arrays.** An alternative to using the `[]`

operator for concatenation are the three functions `cat`

, `horzcat`

, and `vertcat`

. With these functions, you can construct matrices (or multidimensional arrays) along a specified dimension. Either of the following commands accomplish the same task as the command `C = [A; B]`

used in the section on Concatenating Matrices:

C = cat(1, A, B); % Concatenate along the first dimension C = vertcat(A, B); % Concatenate vertically

**Replicating a Matrix.** Use the `repmat`

function to create a matrix composed of copies of an existing matrix. When you enter

MATLAB replicates input matrix `M`

`v`

times vertically and `h`

times horizontally. For example, to replicate existing matrix `A`

into a new matrix `B`

, use

A = [8 1 6; 3 5 7; 4 9 2] A = 8 1 6 3 5 7 4 9 2 B = repmat(A, 2, 4) B = 8 1 6 8 1 6 8 1 6 8 1 6 3 5 7 3 5 7 3 5 7 3 5 7 4 9 2 4 9 2 4 9 2 4 9 2 8 1 6 8 1 6 8 1 6 8 1 6 3 5 7 3 5 7 3 5 7 3 5 7 4 9 2 4 9 2 4 9 2 4 9 2

**Creating a Block Diagonal Matrix.** The `blkdiag`

function combines matrices in a diagonal direction, creating what is called a block diagonal matrix. All other elements of the newly created matrix are set to zero:

A = magic(3); B = [-5 -6 -9; -4 -4 -2]; C = eye(2) * 8; D = blkdiag(A, B, C) D = 8 1 6 0 0 0 0 0 3 5 7 0 0 0 0 0 4 9 2 0 0 0 0 0 0 0 0 -5 -6 -9 0 0 0 0 0 -4 -4 -2 0 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 8

Concatenating Matrices | Generating a Numeric Sequence |

© 1994-2005 The MathWorks, Inc.