indexing cell array of arrays

8 ビュー (過去 30 日間)
John Petersen
John Petersen 2013 年 8 月 9 日
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?

採用された回答

Evan
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
Evan 2013 年 8 月 9 日
No problem!
Evan
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 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 8 月 9 日
for k=1:numel(A)
A{k}=A{k}(1:4);
end
  2 件のコメント
Jan
Jan 2013 年 8 月 10 日
I still prefer this due to the speed.
Evan
Evan 2013 年 8 月 10 日
編集済み: Evan 2013 年 8 月 12 日
Yes. I'll make a comment on my answer noting that Azzi's is preferred in all cases except where you want a quick and messy answer.

サインインしてコメントする。


Azzi Abdelmalek
Azzi Abdelmalek 2013 年 8 月 9 日
If A is your cell array
cellfun(@(x) x(1:k),A,'un',0)

Daniel Shub
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 件のコメント
John Petersen
John Petersen 2013 年 8 月 22 日
Why I have a cell array: I'm using textscan to read in a file with strings, integers and floats on each line. example:
data = textscan(fileID,'%s %s %d %f %f');
Daniel Shub
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 ExchangeCell Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by