Reputation: 6298
I have a cell array, where each cell contains an array of strings. An example is as follows:
example = {{['a'], ['b']}, {['c']}}
However,
example{1}
returns a 1x2 cell array, whereas
example{2}
returns a cell, NOT a 1x1 cell array as expected. This single cell value is then not in the same format as the encapsulating example cell array, which breaks calculations further down the line.
How do I fix this? Ideally, I'd like to be able to have a 1x1 cell array and avoid any nasty special cases.
Upvotes: 2
Views: 145
Reputation: 65430
In MATLAB, there is no difference between a scalar entity and a 1 x 1 array. The scalar is simply a 1 x 1 version of the array. There is no special array class, instead an array is simply a list of objects that have the same class. This holds true regardless of whether it's a double
array, a char
array, a struct
array, or in your case a cell
array (more info here).
As such, example{2}
does return a 1 x 1 cell array. You can test example{2}
actually is a 1 x 1 cell by using class
, size
, iscell
, and/or whos
class(example{2})
% cell
size(example{2})
% 1 1
iscell(example{2})
% 1
tmp = example{2};
whos('tmp')
% Name Size Bytes Class Attributes
%
% tmp 1x1 114 cell
Since it is a 1 x 1 cell array, the rest of your code should be able to handle it without any problems (assuming you wrote the rest of the code correctly).
Upvotes: 3
Reputation: 22225
A one-element cell array is still a cell array of size 1x1. Observe:
>> class(example{1})
ans =
cell
>> class(example{2})
ans =
cell
>> size(example{1})
ans =
1 2
>> size(example{2})
ans =
1 1
You can either test separately if your array is of size 1x1 in particular further down your code, or, consider whether indexing the cell array by ()
syntax somehow is more beneficial for you, e.g.:
>> example(1)
ans =
{1x2 cell}
>> example(2)
ans =
{1x1 cell}
Upvotes: 2