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

조회 수: 20 (최근 30일)
dave
dave 2018년 3월 14일
댓글: Kafayat Olayinka 2019년 2월 9일
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

채택된 답변

Birdman
Birdman 2018년 3월 14일
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))

추가 답변 (2개)

Jos (10584)
Jos (10584) 2018년 3월 14일
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 2018년 3월 14일
Thanks for the comments
I have not tried padcat ... but I will give I try
thanks for the suggestion

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by