indexing cell array of arrays
조회 수: 9 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
Evan
2013년 8월 9일
편집: Evan
2013년 8월 9일
cellfun(@(x)x(1:K),C,'uni',0) %Where C is your original cell array
댓글 수: 3
Evan
2013년 8월 10일
편집: Evan
2013년 8월 10일
Note that, when using implicit functions with cellfun, operation will often be slower than a FOR LOOP would be (this is because cellfun has to do the looping anyway, plus some overhead). So, in cases where you're working with large arrays and/or operation time is quite important, my method above is not ideal.
추가 답변 (3개)
Daniel Shub
2013년 8월 9일
편집: Daniel Shub
2013년 8월 23일
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
Daniel Shub
2013년 8월 23일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Cell Arrays에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!