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일

0 개 추천

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.
Andrei Bobrov
Andrei Bobrov 2011년 12월 1일
Thank you Jan!

댓글을 달려면 로그인하십시오.

Jan
Jan 2011년 12월 1일

0 개 추천

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에 대해 자세히 알아보기

질문:

2011년 12월 1일

Community Treasure Hunt

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

Start Hunting!

Translated by