How can I access element with same index from multiple cells

6 Ansichten (letzte 30 Tage)
Hu
Hu am 21 Okt. 2013
Kommentiert: Cedric am 21 Okt. 2013
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 ?

Akzeptierte Antwort

Cedric
Cedric am 21 Okt. 2013
Bearbeitet: Cedric am 21 Okt. 2013
>> 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.

Weitere Antworten (1)

Arturo Moncada-Torres
Arturo Moncada-Torres am 21 Okt. 2013
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.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by