How can I access element with same index from multiple cells

10 ビュー (過去 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.
  2 件のコメント
Hu
Hu 2013 年 10 月 21 日
Thanks!
Cedric
Cedric 2013 年 10 月 21 日
You're welcome.

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by