Adding information to a cell array without using a loop?
古いコメントを表示
Hi all,
Hopefully there is a built-in function for this that I'm not finding.
I currently have an array of length Nx2. Let's say for example that it looks like this:
Array=
[1 2
1 7
1 9
2 3
2 4
4 1
5 8
5 9]
I want to make a cell array of size(max(Array(:,1)),1). So in this case it would be 5x1. Then, I want to cycle through Array and add the number in the 2nd column into the corresponding cell from the first column. In a loop, I would do it like this:
C=cell(max(Array(:,1),1);
for i=1:length(C)
C{i}=Array(Array(:,1)==i,2);
end
The result would look like this:
C=
[2 7 9] [3 4] [ ] [1] [8 9]
My problem is that I have a very big array, about 100k in length. Is there a faster way of doing this without running a loop through? Perhaps using cellfun() or something similar?
Thanks in advance!
採用された回答
その他の回答 (1 件)
Azzi Abdelmalek
2013 年 11 月 5 日
編集済み: Azzi Abdelmalek
2013 年 11 月 5 日
[a,b,c]=unique(Array(:,1));
C=accumarray(c,Array(:,2), size(a), @(x) {x});
celldisp(C)
%You can add
C1=cell(max(a),1)
C1(a)=C
celldisp(C1)
カテゴリ
ヘルプ センター および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!