get specific elements from all non-empty cells

조회 수: 10 (최근 30일)
Timo W
Timo W 2013년 6월 12일
Hello everyone!
I have a pretty simple task, but I cannot come up with a simple solution. All my ideas seem way to complicated. Here is what I want to do:
I have a cell array C containing vectors of equal length or empty cells:
C = {[1 2 3];
[];
[];
[5 6 7];
[]};
Now I want to get a specific element, for example the second element, of each cell and write it into a new variable A. If the cell is empty I just want to write empty in the corresponding cell in A:
So if I wanted to get the second element I would expect A to look like this:
A =
[2]
[]
[]
[6]
[]
Thanks in advance!
EDIT
Well, maybe there is not such an obvious solution for this. So I'll just stick to an 'if' and a 'for' loop.

채택된 답변

Andrei Bobrov
Andrei Bobrov 2013년 6월 14일
편집: Andrei Bobrov 2013년 6월 14일
A = cell(size(A));
ii = ~cellfun('isempty',C);
A(ii) = cellfun(@(x)x(2),C(ii),'un',0);
or use loop for..end
A = cell(size(C));
for jj = 1:numel(C)
if ~isempty(C{jj})
A{jj} = C{jj}(2);
end
end
  댓글 수: 1
Timo W
Timo W 2013년 6월 16일
I thought there might be a nice "one line solution". But maybe such a solution does not exist. Thanks though!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by