Why is the cell array structure in Matlab not behaving well and keep constructing vectors?

Viewed 137

Let's say I have two simple vectors;

vec1=[1,2,3];
vec2=[4,5,6];

Now I make a cell array from them.

cellArray1={vec1,vec2}

If I want to create a 2x3 numerical array, it is simple.

[vec1;vec2]
%or
[cellArray1{1};cellArray{2}]

However, to make a 2x3 cell array from the above, it is not behaving as expected.

{vec1(1,:);vex2(1,:)}
{cellArray1{1};cellArray1{2}}
{cellArray1{1}(1,:),cellArray1(1,:)}

None give me a 2x3 cell array. Why is that so and how to make a 2x3 cell array containing only the double values in each of its entries in a very formal and efficient way. I don't think using cell2mat or writing a code to write another dot m file with {~,~,~;~,~,~} which running the resulting new file creates the cell array of interest, are good practices.

2 Answers

This is by design.

Cell arrays can contain anything, and therefore the language is not optimized to interpret that things are the same shape.

if size(vec1(1,:)) is 1x1 and size(vex2(1,:)) is 1x50, the following should still work (unlike with []).

{vec1(1,:);vex2(1,:)}

if cellArray1{1} is a figure handle and cellArray1{2} is a string, the following should still work (unlike with []).

{cellArray1{1};cellArray1{2}}

See first example to know why this should work with any shape:

{cellArray1{1}(1,:),cellArray1(1,:)}

Cell arrays accept many things as input, no problem. So they can not assume that what you are inputing to create the cell is a 1x3 numerical array, and therefore they can not behave as if it were and create a 2x3 cell array. Even if they could check for that and act accordingly, then you would have inconsistent behavior depends on the length of the numerical vector that comes in.

Square brackets can instead actually assume that both vectors are the same size, and error otherwise.

Consider Cell arrays as list that can contain anything in each element, not numerical arrays. If you have stuff that is only numerical arrays, the recommendations is that you use that, vectors/matrices, and not cell arrays.

Here is one way to get the data structure that I wanted in the question without using cell2mat or a code-file-writing and then running the written code-file.

[num2cell(cellArray1{1});num2cell(cellArray1{2})]
% or
vertcat(num2cell(cellArray1{1}),num2cell(cellArray1{2}))
Related