Thanks this was useful. This script is slow only because of the first double for-loop doing a dynamic memory allocation each time the condition is met. MATLAB is terrible with dynamic memory allocations. Simply add:
Ciny = zeros(1,x*y);
right before the outer for loop (for i=1:x), and then add:
Ciny(cnt:end) = ;
right at the end of the for loop (right above cnt=cnt-1; and then the sort) to get rid of the unused memory. This speeds up the code tremendously.