フィルターのクリア

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

29 ビュー (過去 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 Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by