I have this cell array of chars:
a={'1';'1';'1';'1';'1';'3';'3';'3';'3';'3';'3';'4';'4';'4';'4'};
and I want to transform it into this:
a={'1';'';'';'';'';'3';'';'';'';'';'';'4';'';'';''};
First, find the unique elements of a and their first indices. Then set all other entries of a to ''.
[~, ii] = unique(a);
ind = setdiff(1:numel(a), ii);
[a{ind}] = deal('');
As pointed out by CST-Link, both the computation of duplicate indices and assignment of empty strings can be sped up (in particular, setdiff is slow):
[~, ii] = unique(a);
ind = 1:numel(a);
ind(ii) = [];
a(ind) = {''};
rle would do, interestingly (or not :-) )This could be fast for large arrays:
a=repmat({'1';'1';'1';'1';'1';'3';'3';'3';'3';'3';'3';'4';'4';'4';'4'}, 100000, 1);
[u,n] = unique(flipud(a));
b = repmat({''}, size(a));
b(n) = u;
a = flipud(b);
repmat is typically known for its lack of speed. Do you have any evidence that this pays off for large arrays?:)repmat is O(1) though it has a large overhead, while unique is O(n*log(n)). I changed the code for a large array a so you can profile it yourself. Try smaller or larger values for the number of duplicates in the definition of a; please let me know if you got different complexities.a my code ran in 0.9 seconds, while the other ran in 1.4 seconds (MATLAB R2012a, i5, 3Gb RAM). I hope that this is evidence enough. :-)deal is the bottleneck...
a = {'1','1','2','2','1','1'}do you delete three "1"s or just the followers in each group?