Effacer les filtres
Effacer les filtres

How can I access element with same index from multiple cells

8 vues (au cours des 30 derniers jours)
Hu
Hu le 21 Oct 2013
Commenté : Cedric le 21 Oct 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 ?

Réponse acceptée

Cedric
Cedric le 21 Oct 2013
Modifié(e) : Cedric le 21 Oct 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.
  2 commentaires
Hu
Hu le 21 Oct 2013
Thanks!
Cedric
Cedric le 21 Oct 2013
You're welcome.

Connectez-vous pour commenter.

Plus de réponses (1)

Arturo Moncada-Torres
Arturo Moncada-Torres le 21 Oct 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.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by