In an array of numbers (0 to 255 of data type uint8), if any number occurs more than 3 times, I would like to insert number '255' (uint8) in between the array and return the position where '255' was inserted. Can somebody please help me?

7 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
  2 Comments
Image Analyst
Image Analyst on 11 Feb 2015
Seems like a quirky thing to want to do. Like a sort of manual watershed segmentation. Why do you want to do that? Also, don't use input as the name of a variable since it's already the name of a built-in function.

Sign in to comment.

Accepted Answer

Guillaume
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))

More Answers (0)

Categories

Find more on Images in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!