getting first element of each cell array with different sizes

조회 수: 128 (최근 30일)
sensation
sensation 2017년 10월 18일
댓글: Stephen23 2019년 7월 10일
Hi,
I have a 205 x 1 cell with diffferent sizes and I want to extract only the first element of each cell. For example, I have:
[8,14]
[10,14,15]
[9,14]
[5,14] etc till 205
and the result should be:
8
10
9
5.
Thanks a lot!
M.

채택된 답변

Stephen23
Stephen23 2017년 10월 18일
편집: Stephen23 2017년 10월 18일
>> C = {[8,14];[10,14,15];[9,14];[5,14]};
>> cellfun(@(v)v(1),C)
ans =
8
10
9
5
  댓글 수: 1
Stephen23
Stephen23 2017년 10월 18일
And to allow for empty arrays:
>> C = {[8,14];[10,14,15];[9,14];[5,14];[]};
>> idx = ~cellfun('isempty',C);
>> out = zeros(size(C));
>> out(idx) = cellfun(@(v)v(1),C(idx))
out =
8
10
9
5
0

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

추가 답변 (2개)

Christian Keine
Christian Keine 2017년 10월 18일
There are at least two possible ways this could be done. First, you could loop through the cell array and extract the first value of each cell. This is, however, probably not the most elegant or fastest solution. The second option is to use cellfun in combination with an anonymous function which extracts only the first value of each cell, which should work faster for large arrays and is easier to read.
To do so, first define the function that should be executed for each cell:
fun = @(x) x(1)
Then apply this function to each cell in the array using cellfun with x being you cell array
firstElement = cellfun(fun,x)
Using your data it would look like this:
x = {[8,14],[10,14,15],[9,14],[5,14]}
fun = @(x) x(1)
firstElement = cellfun(fun,x)
Hope this is helpful.
  댓글 수: 3
sensation
sensation 2017년 10월 18일
Just saw that I have in my data instead of number I have nan someties like:
[8,14]
[10,14,15]
[]
[9,14].
Do you know how to include also this in a way to put zero in an output if there is nothing in a cell like?
8
10
0
9
Thanks!
Stephen23
Stephen23 2017년 10월 18일
@sensation: see my comment, which shows exactly how to do this.

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


Daniel  Rieger
Daniel Rieger 2019년 7월 10일
편집: Daniel Rieger 2019년 7월 10일
Hello guys,
what if i only want to obtain the first entry of the first cell?
Or more general: what if i want a specific entry not for each but only for one cell?
I could also use and then cut out the entries that i dont need, but is there a more elegant way?
% N: wanted entry
all_entry = cellfun(@(v)v(1),C)
wanted_entry = all_entry(N)

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by