Adding information to a cell array without using a loop?
Afficher commentaires plus anciens
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!
Réponse acceptée
Plus de réponses (1)
Azzi Abdelmalek
le 5 Nov 2013
Modifié(e) : Azzi Abdelmalek
le 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)
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!