MATLAB: How to speed up simple sorting

findfor loopsortingspeed up

Hello, I got two variables (Units and time points) that needs to me sorted with respect to each other. Meaning, I want to sort all the time points to its specific Unit. With large numbers of Units and many time points this sorting takes forever. Is there a way to speed this up?
What I got so far works, but it is rather slow:
%Prepare example RAW data
Unit=int32(randi(60,5000000,1)); %60 Units in an order, that matches the timepoints
timepoints=randi(600,5000000,1); %5*10^6 Timepoints (from a range of 600ms) in an order, that corresponds to the according unit
%Prepare the variable where the data should be sorted
for i=1:60
Unit_sort{i,1}=i;
Unit_sort{i,2}=[];
end
%Sort "time points" to the according "Unit"
for i=1:length(timepoints)
index = find([Unit_sort{:,1}] == Unit(i));
Unit_sort{index,2}=[Unit_sort{index,2} timepoints(i)];
end

Best Answer

2 general rules:
  • Pre-allocate the output. The iterative growing of arrays is a Don't!
  • Prefer to run the loop over the smaller array.
uUnit = unique(Unit);
Unit_sort = cell(1, length(uUnit));
for k = 1:length(uUnit)
Unit_sort{k} = timepoints(Unit == uUnit(k));
end
Perhaps this does what you want - I'm not sure because your posted code does not run and I cannot guess, what the wanted result is. But if it runs, read the docs of splitapply and accumarray.