 <p>A very similar answer to @Suever, using a loop and logical matrix rather than cells</p> <pre><code>a = [3 3 5 5 20 20 20 4 4 4 2 2 2 10 10 10 6 6 1 1 1]; vals = unique(a); %find unique values vals = vals(randperm(length(vals))); %shuffle vals matrix aout = []; %initialize output matrix for ii = 1:length(vals) aout = [aout a(a==(vals(ii)))]; %add correct number of each value end </code></pre>