4 views (last 30 days)

Example:

input = [1 255 0 0 0 9 9 9 1 6 6 6 6 6 6 1]; % array of numbers (uint8)

output = [1 255 0 0 0 255 9 9 9 255 1 6 6 6 255 6 6 6 255 1];

% output must have 255 inserted at positions 6, 10, 15, 19 because 0, 9, 6, 6 have occurred three times respectively

outputIndex = [6 10 15 19]; % outputIndex must indicate the positions where 255 was inserted

Guillaume
on 11 Feb 2015

Use diff and strfind (which works with numbers as well) to find your runs. The tricky bit is making sure you don't include the same number in two sequences for sequences longer than 3:

input = [1 255 0 0 0 9 9 9 1 6 6 6 6 6 6 1]

runstarts = strfind(diff(input), [0 0]);

%for sequence of more than 3 it returns indices of overlapping sequence.

%note that from the wording of your question, I would understand that only

%one number should be returned whatever the length of the sequence, in which case:

%runstarts([false diff(runstarts) < 3]) = []

%takes care of it. But according to your example, you define a new sequence

%after just three repeats, in which case:

posoverlap = find(diff(runstarts) < 3, 1);

while posoverlap

runstarts(posoverlap + 1) = [];

posoverlap = find(diff(runstarts) < 3, 1);

end

runends = runstarts + 2;

To insert the 255, I would then convert the array into subarrays using mat2cell and the power of matlab's indexing:

subinput = mat2cell(input, 1, diff([0 runends numel(input)])); %split at the end of each run

subinput(2, :) = {255}; %add a row of 255

subinput(end) = []; %replace last 255 with empty

output = [subinput{:}]; %use indexing + cell expansion to list to reshape into a matrix

outputindex = runends + (1:numel(runends))

Opportunities for recent engineering grads.

Apply TodayFind the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
## 2 Comments

## Direct link to this comment

https://ww2.mathworks.cn/matlabcentral/answers/177465-in-an-array-of-numbers-0-to-255-of-data-type-uint8-if-any-number-occurs-more-than-3-times-i-woul#comment_265562

⋮## Direct link to this comment

https://ww2.mathworks.cn/matlabcentral/answers/177465-in-an-array-of-numbers-0-to-255-of-data-type-uint8-if-any-number-occurs-more-than-3-times-i-woul#comment_265562

## Direct link to this comment

https://ww2.mathworks.cn/matlabcentral/answers/177465-in-an-array-of-numbers-0-to-255-of-data-type-uint8-if-any-number-occurs-more-than-3-times-i-woul#comment_265571

⋮## Direct link to this comment

https://ww2.mathworks.cn/matlabcentral/answers/177465-in-an-array-of-numbers-0-to-255-of-data-type-uint8-if-any-number-occurs-more-than-3-times-i-woul#comment_265571

Sign in to comment.