I have this cell array
>> FooCellArray
FooCellArray =
1×7 cell array
Columns 1 through 4
{'Foo1'} {'Foo2'} {'Foo3'} {'Foo4'}
Columns 5 through 7
{'Foo5'} {'Foo6'} {'Foo7'}
cell2mat()
converts the array into a character array instead of a 1x7 or 7x1 matrix of 'Foo1'
... 'Foo7'
.
>> (cell2mat(FooCellArray))'
ans =
28×1 char array
'F'
'o'
'o'
'1'
'F'
'o'
'o'
'2'
'F'
'o'
'o'
'3'
'F'
'o'
'o'
'4'
....
Why?
CodePudding user response:
cell2mat
is doing precisely the correct thing as documented here. Each cell
element is char
vector of size 1xN. Your overall cell
array is 1xN. cell2mat
concatenates the contents of every cell in the "natural" direction as defined by the shape of the cell
array. Your original cell
looks a bit like this:
FooCellArray = [{'Foo1'}, {'Foo2'}]
The effect of cell2mat
is basically as if you removed the {}
, so you're left with
cell2mat(FooCellArray) --> ['Foo1', 'Foo2']
And therefore this gets concatenated into a single char
vector 'Foo1Foo2'
.
Compare with vectors of double
instead of vectors of char
:
>> FooCellArray = [{[1,2,3]}, {[4,5,6]}]
FooCellArray =
1×2 cell array
{[1 2 3]} {[4 5 6]}
>> cell2mat(FooCellArray)
ans =
1 2 3 4 5 6
CodePudding user response:
A 7x4 matrix would make sense in this particular case, as the contents are characters. However, MATLAB cannot do that by default.
Consider the case where your second string would be foo12
instead. You'd have one 1x5 character array amidst 6 1x4 character arrays. That doesn't fit into a neat M-by-N matrix. So all MATLAB can do, is lash everything together as an N-by-1 array.