how do I convert a cell array of different size cells to a matrix

20 visualizaciones (últimos 30 días)
suppose I have a cell array of cells:
c = {{1 2}; {1 2 3};{4 5 6};{10 11 12 12 14}};
What is the best way to convert this to a matrix?
This is what I have come up with:
M = max(cellfun(@numel, c));
c2 = cellfun(@(row)[row (cell(1,M-numel(row)))], c, 'uni', 0);
for idx = 1:numel(c2)
c2{idx}(cellfun(@isempty, c2{idx})) = {0};
end
c3=vertcat(c2{:});
this seems like an easy thing to do, but I feel I overcomplicated the code. Is this the best way to do it?
Ultimately I'm expecting to have a matrix array that looks like this:
1 2 0 0 0
1 2 3 0 0
4 5 6 0 0
10 11 12 12 14
my goal is to exclude the zeros and count the number of repeat occurences per column...
I.e. in the example above
col1UniqueSorted values = [1 4 10]
col1NumberOfHits= [2 1 1]
col2UniqueSorted values = [2 5 11]
col2NumberOfHits= [2 1 1]
etc ...
I managed to get the results I need, but just looking for a cleaner or better way to do it. if I can get the answer working directly with cells, I'm will to try that too, I just was not able to figure it out.
thanks

Respuesta aceptada

Birdman
Birdman el 14 de Mzo. de 2018
Just one line, which is an improvement of your code:
maxEl=5;%max number of elements of a cell element in your cell
C=cell2mat(cellfun(@(x) [cell2mat(x) zeros(1,maxEl-numel(x))],c,'uni',0))

Más respuestas (2)

Jos (10584)
Jos (10584) el 14 de Mzo. de 2018
An easy job for padcat :)
c = {{1 2}; {1 2 3};{4 5 6};{10 11 12 12 14}}
% rather awkward cell array of cell arrays of numeric arrays ...
% engine
c2 = cellfun(@(x) [x{:}], c, 'un',0) % convert to cell array of numeric array
[m, tf] = padcat(c2{:}) % concatenate, pad rows with NaNs
m(~tf) = 0 % replace NaNs by zeros

dave
dave el 14 de Mzo. de 2018
Thanks for the comments
I have not tried padcat ... but I will give I try
thanks for the suggestion

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by