The cell with the max number of elements

3 views (last 30 days)
I have 1x8 cell array and I want t get the cell with the max number of elements for example for the following cell array
I need the answer to be cell number 7 can I do this with function max?

Accepted Answer

James Tursa
James Tursa on 4 May 2015
>> c = {1 [1,2] [1,3] [1,2,4] [1,2,4,5] [1,6] [1,2,4,5,7] nan}
c =
[1] [1x2 double] [1x2 double] [1x3 double] [1x4 double] [1x2 double] [1x5 double] [NaN]
>> [~,x] = max(cellfun(@numel,c))
x =
7
  8 Comments
Titus Edelhofer
Titus Edelhofer on 5 May 2015
Hi Maro,
this is the time I guess where a loop will be easier than trying to do this in a one liner, something like
res = zeros(1, size(c,2));
for i=1:length(res)
val = c(:, i);
% skip NaN
idxNaN = find(~cellfun(@(x) numel(x)==1 && isnan(x), val, 'UniformOutput', true));
% look for min in "allowed cells only"
[~,x] = min(cellfun(@numel,val(idxNaN)));
% be careful with the indices:
res(i) = idxNaN(x);
end
Admittedly not tested ...
Titus
Maro
Maro on 6 May 2015
Hi, I have found more efficient solution..
L=cellfun(@numel,c);
L(L== 1) = Inf;
[~,x]=min(L,[],2);

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!