cell arrey

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]....}.

回答(2 个)

Andrei Bobrov
Andrei Bobrov 2011-12-1
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 个评论

Jan
Jan 2011-12-1
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.
Thank you Jan!

请先登录,再进行评论。

Jan
Jan 2011-12-1
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

类别

帮助中心File Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by