Effacer les filtres
Effacer les filtres

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

2 vues (au cours des 30 derniers jours)
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!

Réponse acceptée

Adam
Adam le 15 Déc 2014
Modifié(e) : Adam le 15 Déc 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 commentaires
Adam
Adam le 15 Déc 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 le 15 Déc 2014
Aha! My original 'C' was a 4x1 cell - when I transposed it, this solution worked perfectly. Thank you!

Connectez-vous pour commenter.

Plus de réponses (1)

Guillaume
Guillaume le 15 Déc 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))

Catégories

En savoir plus sur Cell Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by