MATLAB: Does concatenation with cell arrays and doubles not work in multiple dimensions

MATLAB

The following code produces a concatenation error for the multi-dimensional case:
[{'foo'} 2]
[{'foo'} 1; 1 2]
This results in the following error:
??? Error using ==> vertcat
CAT arguments dimensions are not consistent.

Best Answer

The results are expected from the given example code. When you concatenate [{'foo'} 1; 1 2], MATLAB will take the following steps:
1. The first row is concatenated together: [{'foo'} 1] becomes a 1x2 cell array: 'foo' [1]
2. Second row concatenated: becomes 1x2 double.
3. Second row is converted to type of first row: becomes a 1x1 cell array containing a 1x2 double.
4. Vertcat attempts to concatenate a 1x2 cell with a 1x1 cell and fails with the given message.
To work around this issue you can first convert the doubles to cells using curly braces or you can create multiple cell arrays with the NUM2CELL command and then concatenate. For example:
[{'foo'} {1}; {1} {2}]
or
a = [{'foo'} 1];
b = num2cell([1 2]);
[a;b]