how do I convert a cell array of different size cells to a matrix
29 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
dave
am 14 Mär. 2018
Kommentiert: Kafayat Olayinka
am 9 Feb. 2019
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
0 Kommentare
Akzeptierte Antwort
Birdman
am 14 Mär. 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))
Weitere Antworten (2)
Jos (10584)
am 14 Mär. 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
padcat can be downloaded from the File Exchange: https://uk.mathworks.com/matlabcentral/fileexchange/22909-padcat-varargin-
0 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!