Adding information to a cell array without using a loop?

1 view (last 30 days)
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!

Accepted Answer

Sean de Wolski
Sean de Wolski on 5 Nov 2013
Edited: Sean de Wolski on 5 Nov 2013
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.

More Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 5 Nov 2013
Edited: Azzi Abdelmalek on 5 Nov 2013
[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 Comments
Jordan
Jordan on 5 Nov 2013
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]

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!