How can I access element with same index from multiple cells

9 次查看(过去 30 天)
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
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