accessing elements inside cell arrays
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
PChoppala
am 1 Dez. 2015
Bearbeitet: PChoppala
am 1 Dez. 2015
I am not a great user of cell arrays and haven't found my answer precisely on other links, hence the question. I have a cell array inside a cell array, e.g., as follows,
x{1}={1 2 3};
x{2}={1 2 3};
x{3}={1 2 3};
x{4}={1 2 3};
x{5}={1 2 3};
Now for example I would like to extract the second element in each 1x3 cell array for all the 5 cell arrays, i.e., I would like to obtain a 5x1 vector containing twos. Currently I obtain this by
temp1 = vertcat(x{:});
result = vertcat(temp1{:,2})
Can this be done more effectively and preferably in a single statement?
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 1 Dez. 2015
result = subsref( cell2mat(vertcat(x{:})), struct('type', '()', 'subs', {{':', 2}}) );
This is why we seldom do it on a single line. Much easier is two lines, either of
col2 = @(M) M(:,2);
result = col2( cell2mat(vertcat(x{:})) );
or
temp2 = cell2mat(vertcat(x{:}));
result = temp2(:,2);
The advantage of the first approach is that the "col2" only needs to be defined once, so you can do similar operations with a single line afterwards
getcol = @(M, col) M(:,col);
result1 = getcol( cell2mat(vertcat(x{:})), 2);
result2 = getcol( cell2mat(vertcat(y{:})), 5);
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Data Type Conversion 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!