Filter löschen
Filter löschen

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

2 Ansichten (letzte 30 Tage)
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!

Akzeptierte Antwort

Adam
Adam am 15 Dez. 2014
Bearbeitet: Adam am 15 Dez. 2014
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 Kommentare
Adam
Adam am 15 Dez. 2014
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 am 15 Dez. 2014
Aha! My original 'C' was a 4x1 cell - when I transposed it, this solution worked perfectly. Thank you!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Guillaume
Guillaume am 15 Dez. 2014
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))

Kategorien

Mehr zu Cell Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by