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 次查看(过去 30 天)
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
Guillaume 2015-2-11
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))

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Images 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by