Show older comments
this cell array contains an element that is only one number, for example cell={[100] [100,30,79,88,28,43,1] [100,91,33,36,54,8,5,2] [100,6,3] [100,91,33,36,54,8,5,2,4] [100,91,33,36,54,8,5] [100,6] [100,9,42,61,11,7] [100,91,33,36,54,8] [100,9] [100,6,3,23,10] [100,9,42,61,11] [100,91,33,36,31,99,12]}
I need to display the second number of each element, if the element doesn't have the second number, it would be 0 or empty instead . for example cell2={[0]{[30] [91] [6] [91]....}.
Answers (2)
Andrei Bobrov
on 1 Dec 2011
C - your cell array
out = num2cell(zeros(size(C)));
t = cellfun('length',C)>1;
out(t) = cellfun(@(x)x(2),C(t),'un',0);
2 Comments
Jan
on 1 Dec 2011
The anonymous function inside CELLFUN is much slower than CELLFUN(@numel,C)>1. But this is much faster: "t = cellfun('prodofsize', C) > 1;"
The CELLFUN commands, which are strings, are evaluated inside the C-mex function, while the function handles need a mexCallMATLAB to call Matlab recursively. Unfortunately modern Matlab versions do not contain teh source file cellfun.c anymore.
Andrei Bobrov
on 1 Dec 2011
Thank you Jan!
Jan
on 1 Dec 2011
C = {[100], [100,30,79,88,28,43,1], [100,91,33,36,54,8,5,2], ...
[100,6,3], [100,91,33,36,54,8,5,2,4], [100,91,33,36,54,8,5] [100,6], ...
[100,9,42,61,11,7] [100,91,33,36,54,8] [100,9] [100,6,3,23,10], ...
[100,9,42,61,11] [100,91,33,36,31,99,12]};
Index = cellfun('length', C) > 1; % Faster than CELLFUN(@length)
D = cell(size(C)); % Pre-allocate
for i = 1:numel(C)
if Index(i)
D{i} = C{i}(2);
else
D{i} = 0;
end
end
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!