Assigning a cell array to a cell of a different cell array

I need to assign a cell array to an element of a different cell array. ie:
child = {'a', 'b', 'c'};
parent = cell(2,1);
parent{1} =child;
This code works when child contains more than one element. However when child contains only one element, the element value is copied rather than a 1x1 cell array. ie:
child = {'a'};
parent = cell(2,1);
parent{1} = child;
In this case printing parent shows that the first element of parent is a string, 'a', rather than a 1x1 cell array. How can I override this behavior?

 Accepted Answer

"This code works when child contains more than one element"
No, it always puts that cell array there, whatever its size. When a cell contains a scalar array then it is displayed differently to non-scalar arrays, but the stored data is still a cell array, exactly as you allocated. You just need to check it:
>> child = {'a', 'b', 'c'};
>> parent = cell(2,1);
>> parent{1} =child;
and lets check it:
>> class(parent{1})
ans = cell
>> size(parent{1})
ans =
1 3
The first cell contains a 1x3 cell array. Now lets try your second example:
>> child = {'a'};
>> parent = cell(2,1);
>> parent{1} = child;
and now lets check what is inside:
>> class(parent{1})
ans = cell
>> size(parent{1})
ans =
1 1
The first cell contains a scalar cell array, exactly as you allocated. Another check is the indexing required to get the value back out:
>> parent{1}{1}
ans = a
Note the different way that MATLAB displays a 1xN char, compared to a char in a cell array.

1 Comment

Hi Stephan,
Thank you for your answer. You are correct. It turns out that the issue was with the software we were trying to interface with.
Regards,
Brandon

Sign in to comment.

More Answers (0)

Categories

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!