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!

 採用された回答

Sean de Wolski
Sean de Wolski 2013 年 11 月 5 日
編集済み: Sean de Wolski 2013 年 11 月 5 日

0 投票

Accumarray!
C = accumarray(Array(:,1),Array(:,2),[],@(x){x}).'
Azzi's solution is typically the safer approach - safeguarding against non-integers and large values. However, for your application using these explicitly does what you want.

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 11 月 5 日
編集済み: Azzi Abdelmalek 2013 年 11 月 5 日

0 投票

[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)

2 件のコメント

Jordan
Jordan 2013 年 11 月 5 日
This seems very close, but what happens in the situation (like above) where I might skip a number? If you look above I want my answer to be this:
C=
[2 7 9] [3 4] [ ] [1] [8 9]
, but this function gives me this, skipping the empty cell:
C=
[2 7 9] [3 4] [1] [8 9]
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 11 月 5 日
You did not see C1

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

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by