Accelerating the pace of engineering and science

• Trials

# mat2cell

Convert array to cell array with potentially different sized cells

## Syntax

C = mat2cell(A,dim1Dist,...,dimNDist)
C = mat2cell(A,rowDist)

## Description

C = mat2cell(A,dim1Dist,...,dimNDist) divides array A into smaller arrays within cell array C. Vectors dim1Dist,...dimNDist specify how to divide the rows, columns, and (when applicable) higher dimensions of A.

C = mat2cell(A,rowDist) divides array A into an n-by-1 cell array C, where n == numel(rowDist).

## Input Arguments

 A Any type of array. dim1Dist,...,dimNDist Numeric vectors that describe how to divide each dimension of A. For example, this command `c = mat2cell(x, [10, 20, 30], [25, 25])` divides a 60-by-50 array into six arrays contained in a cell array. For the kth dimension, sum(dimkDist) == size(A, k). If the kth dimension of A is zero, set the corresponding dimkDist to the empty array, []. For example, ```a = rand(3, 0, 4); c = mat2cell(a, [1, 2], [], [2, 1, 1]);``` rowDist Numeric vector that describes how to divide the rows of A. When you do not specify distributions for any other dimension, the mat2cell function creates an n-by-1 cell array C, where n == numel(rowDist).

## Output Arguments

 C Cell array. The kth dimension of array C is given by size(C, k) == numel(dimkDist). The kth dimension of the ith cell of C is given by size(C{i}, k) == dimkDist(i).

## Examples

Divide the 5-by-4 matrix X into 2-by-3 and 2-by-2 matrices contained in a cell array.

```X = reshape(1:20,5,4)'
C = mat2cell(X, [2 2], [3 2])
celldisp(C)```

This code returns

```X =
1     2     3     4     5
6     7     8     9    10
11    12    13    14    15
16    17    18    19    20

C =
[2x3 double]    [2x2 double]
[2x3 double]    [2x2 double]

C{1,1} =
1     2     3
6     7     8

C{2,1} =
11    12    13
16    17    18

C{1,2} =
4     5
9    10

C{2,2} =
14    15
19    20```

Divide X (created in the previous example) into a 2-by-1 cell array.

```C = mat2cell(X, [1 3])
celldisp(C)```

This code returns

```C =
[1x5 double]
[3x5 double]

C{1} =
1     2     3     4     5

C{2} =
6     7     8     9    10
11    12    13    14    15
16    17    18    19    20```