recipes : programming : Concatenating cell arrays in bulk

Problem

You have stored a large number of matrices in a cell array and want to concatenate them into a single matrix but you don't want to use loops.

SolutionThe solution depends on exactly what output you're after. The following works if all your matrices have the same number of columns and you want to concatenate them such that the number of columns stay the same.

% Make a cell array where each cell contains a 2 by 15 matrix for ii = 1:10 myCell{ii} = rand(2,15); end % You can produce a single 20 by 15 matrix as follows: vertcat(myCell{:})

The vertcat command achieves the same thing as [M1;M2;M3]. Its sister function, horzcat, is the same as [M1,M2,M3]. So vertcat concatenates along the first dimension (rows) and horzcat along the second (columns). Like most MATLAB operations, there is a function which generalises the concatenation to any arbitrary dimension. This function is called cat. So vertcat(myCell{:}) can also be written as cat(1,myCell{:}), since vertcat concatenates along the first dimension. If we wanted to concatenate myCell along the second dimension we would do cat(2,myCell{:}).

Perhaps you're wondering why we use myCell{:} instead of myCell. Try typing each into MATLAB's command prompt and see what happens. myCell returns a list of the sort of data found in each cell but doesn't tell you what those data are. myCell{:}, on the other hand, retrieves the contents of each cell (one at a time) and displays it all on the screen. Similarly, typing myCell(1) simply causes MATLAB to report that the cell contains a 2x15 double; typing myCell{1}, on the other hand, returns the 2 by 15 array.

The use of { } for cell arrays, which doesn't occur elsewhere, can be a little confusing at first. In order to remember the difference between ( ) and { }, it helps to understand what's going on under the hood. Let's consider what happens with a regular array (not a cell array). When you type myArray(1), you're asking MATLAB to return what is stored in RAM at the first location in myArray. Typically this will be a double-precision number. The round brackets work *the same way* for cell arrays: myCell(1) returns what is stored in RAM in first location (the first cell, if you like) of myCell. The key point is *what* is stored there. It is not the data! Instead, it's the address telling the computer where to find the data. So a cell array is really an array of memory addresses. Therefore, when you type myCell(1), MATLAB doesn't return the data. It just tells you what sort of data this cell points to. To get the data you use the curly brackets: myCell{1}. *Now* you're asking MATLAB to retrieve the data which the first element of myCell points to. To re-cap: myCell(1) is like looking up a name in the phone-book (it tells you who lives at an address). myCell{1} is like going to that address and opening the door to meet the person.