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

Réponses (2)

Andrei Bobrov
Andrei Bobrov le 1 Déc 2011

0 votes

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 commentaires

Jan
Jan le 1 Déc 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
Andrei Bobrov le 1 Déc 2011
Thank you Jan!

Connectez-vous pour commenter.

Jan
Jan le 1 Déc 2011

0 votes

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

Catégories

En savoir plus sur Function Creation dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by