MATLAB Examples

Example Using Cell Arrays to Concatenate a list of Vectors

Often in processing data, you have the problem of 4-5 files of data and you need concatenate all those files together. An elegant and easy way to handle this is with cell arrays. Other ways require some guess of how much memory to preallocate

Read in the Data to Cell Array

```clc; clear; % find the input files files = dir('file*.mat'); nFiles = length(files); % setup the cell array c = cell(nFiles, 1); % loop over files putting each file into the corresponding cell for iFile = 1:nFiles load(files(iFile).name); c{iFile} = a; end ```

Horizontal Concatenation

concatenate all the cells of c together

```d = horzcat(c{:}); % alternative equivalent calls % c= [c{:}]; display(d) ```
```d = Columns 1 through 6 1 2 3 11 12 13 Columns 7 through 12 101 102 103 1001 1002 1003 ```

Vertical Concatenation

```% each cell of c is horizontal. Make them vertical c = cellfun(@(x) reshape(x,[],1), c, 'UniformOutput', false); % alternative equivalent calls % c = cellfun(@(x) x(:), c, 'UniformOutput', false); % concatenate vertically d = vertcat(c{:}); display(d) ```
```d = 1 2 3 11 12 13 101 102 103 1001 1002 1003 ```

Concatenation along higher dimensions

```% convert each cell to a 3d array c = cellfun(@(x) reshape(x,1,1,[]), c, 'UniformOutput', false); % concatenate along 3rd dimension d = cat(3, c{:}); display(d) ```
```d(:,:,1) = 1 d(:,:,2) = 2 d(:,:,3) = 3 d(:,:,4) = 11 d(:,:,5) = 12 d(:,:,6) = 13 d(:,:,7) = 101 d(:,:,8) = 102 d(:,:,9) = 103 d(:,:,10) = 1001 d(:,:,11) = 1002 d(:,:,12) = 1003 ```