필터 지우기
필터 지우기

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
Henry Hallock
Henry Hallock 2014년 12월 15일
Aha! My original 'C' was a 4x1 cell - when I transposed it, this solution worked perfectly. Thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (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