How can I access element with same index from multiple cells

조회 수: 5 (최근 30일)
Hu
Hu 2013년 10월 21일
댓글: Cedric 2013년 10월 21일
For example, we have
a = cell(2,2);
a{1} = 1:4;
a{2} = 1:4;
a{3} = 1:4;
a{4} = 1:4;
How can we access like
a{:}(1)
to extract all first elements in cells a ?

채택된 답변

Cedric
Cedric 2013년 10월 21일
편집: Cedric 2013년 10월 21일
>> extract = @(C, k) cellfun(@(c)c(k), C) ;
>> extract(a, 1)
ans =
1 1
1 1
>> extract(a, 3)
ans =
3 3
3 3
if you want to make a lightweight function for extracting various elements of various cell arrays, or simply
>> cellfun(@(c)c(1), a)
ans =
1 1
1 1
if it is just for cell array a and you are fine with hard coding the element # in the expression.

추가 답변 (1개)

Arturo Moncada-Torres
Arturo Moncada-Torres 2013년 10월 21일
I suggest you to use cellfun, which applies a function to each element of a cell array. In your case, it would be something like this:
% Original cell.
a = cell(2,2);
a{1} = 1:4;
a{2} = 1:4;
a{3} = 1:4;
a{4} = 1:4;
% Choose element to extract.
elementToExtract = 1;
% Actually extract the chosen element of all the cells in a.
cellfun(@(x) x(elementToExtract ), a)
Hope it helps.

카테고리

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