indexing cell array of arrays
Show older comments
I have a cell array with M arrays of [Nx1] elements in each cell. How do I create a cell array with the same M arrays but with the first K elements of each cell?
Accepted Answer
More Answers (3)
Azzi Abdelmalek
on 9 Aug 2013
for k=1:numel(A)
A{k}=A{k}(1:4);
end
Azzi Abdelmalek
on 9 Aug 2013
If A is your cell array
cellfun(@(x) x(1:k),A,'un',0)
Daniel Shub
on 9 Aug 2013
Edited: Daniel Shub
on 23 Aug 2013
It is not clear why you have a cell array with each element having Nx1 data, but if all the Nx1 arrays are the same type you can use CELL2MAT. Sticking with the one line answers:
mat2cell(subsref(cell2mat(x), struct('type', {'()'}, 'subs', {{1:K, ':'}})), K, ones(M, 1));
where x is your cell array.
If the M Nx1 arrays are different classes, for example from the output of
data = textscan(fileID,'%s %s %d %f %f');
I would convert my cell array into a structure array with meaningful field names
tempCellMat = cellfun(@(x)mat2cell(x, ones(length(x), 1), 1), data, 'UniformOutput', false);
structArray = cell2struct([tempCellMat{:}], {'Name','dateStr','age','weight','height'}, 2);
You can then do structArray(1:k).
2 Comments
John Petersen
on 22 Aug 2013
Daniel Shub
on 23 Aug 2013
Ahh, so each of your M arrays of [Nx1] elements is of a potentially different class. This means you cannot use CELL2MAT and my answer will not work.... See my edit.
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!