How can I concatenate matrices with different dimensions in a cell array to a numeric array?

2 次查看(过去 30 天)
Hello everybody,
I have a cell array, C:
celldisp(C);
C{1} =
NaN
C{2} =
2068 2069
C{3} =
2300 2301 2302 2303
C{4} =
NaN
in which each cell has different dimensions (as you can see, some cells contain NaN's). I wish to convert this cell to a 1-row numeric array (A), which would look like:
A = [NaN 2068 2069 2300 2301 2302 2303 NaN]
Thank you!

采纳的回答

Adam
Adam 2014-12-15
编辑:Adam 2014-12-15
cell2mat(C);
Note though that this will only work if all cells of c contain row arrays as in your example. If there are also column arrays or randomly sized arrays a different solution is required.
If that is the case you should amend your example to ensure it covers the most complex case you wish to solve since providing a solution that over-solves the problem is a waste of time, hence the above works in the case you showed, but not in any generalised case.
  3 个评论
Adam
Adam 2014-12-15
Are you using it on the data you gave in the first post? Because that is the data I typed in for each cell, resulting in:
>> celldisp(c)
c{1} =
NaN
c{2} =
2068 2069
c{3} =
2300 2301 2302 2303
c{4} =
NaN
followed by:
>> cell2mat( c )
ans =
NaN 2068 2069 2300 2301 2302 2303 NaN

请先登录,再进行评论。

更多回答(1 个)

Guillaume
Guillaume 2014-12-15
If you get an error with a plain cell2mat, that is because some of the cells are not row vector as Adam suggested.
This will flatten the content of all the cells, so will work regardless the content of the cell, be it a column or row vector or a matrix of any dimension:
c = {1, [2 3 4], [5 7 9; 6 8 9], [10 11 12]'}; %for example
cell2mat(cellfun(@(m) m(:).', c, 'UniformOutput', false))

类别

Help CenterFile Exchange 中查找有关 Cell Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by