Add missing numbers of 0's and 1's in an array

1 view (last 30 days)
hello, I have a sequence of 1's and o's values.
Example: I have an 1D array which looks like:
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0]
What I want is to count elements connected to each other and if(mod(elements connected to each other ,10)>5 then add (10-mod) of 1's or 0's
the result can be something like this:
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0].
  1 Comment
Walter Roberson
Walter Roberson on 26 Sep 2021
Edited: Walter Roberson on 26 Sep 2021
Jan has a File Exchange contribution for Run Length Encoding.
Once you know the counts, it is easy to modify the counts in the data and then ask to do run length decoding.

Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 26 Sep 2021
M = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0];
zstarts = strfind([1 M], [1 0])
zstarts = 1×2
1 24
zend = strfind([M 1], [0 1])
zend = 1×2
16 31
zlengths = zend - zstarts + 1
zlengths = 1×2
16 8
ostarts = strfind([0 M], [0 1])
ostarts = 17
oends = strfind([M 0], [1 0])
oends = 23
olengths = oends - ostarts + 1
olengths = 7
if zstarts(1) ~= 1; zlengths = [0 zlengths]; end
runs(1:2:length(zlengths)*2-1) = zlengths;
runs(2:2:length(olengths)*2) = olengths;
mods = mod(runs,10);
mask = mods > 5;
runs(mask) = ceil(runs(mask)/10)*10;
runs
runs = 1×3
20 10 10
elements = zeros(1,length(runs));
elements(2:2:end) = 1;
newM = repelem(elements, 1, runs);
num2str(newM)
ans = '0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0'

Akira Agata
Akira Agata on 26 Sep 2021
How about the following?
% Sample data
x = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0];
% Calculate run-length for each element
idx = diff(x) ~= 0;
idx = [true,idx];
g = cumsum(idx);
group = g(idx)';
element = x(idx)';
lengthIn = accumarray(g',1);
% if mod(length,10)>5, add(10-mod(...))
lengthOut = lengthIn;
idx = mod(lengthIn,10) > 5;
lengthOut(idx) = lengthOut(idx) + (10-mod(lengthIn(idx),10));
% Summarize the result
tSummary = table(group,element,lengthIn,lengthOut);
% >> tSummary
% tSummary =
% 3×4 table
% group element lengthIn lengthOut
% _____ _______ ________ _________
% 1 0 16 20
% 2 1 7 10
% 3 0 8 10
% Then, create the output based on the tSummary
c = arrayfun(@(ele,len)repelem(ele,1,len), tSummary.element, tSummary.lengthOut,...
'UniformOutput', false)
x2 = cell2mat(c');

Categories

Find more on Software Development Tools 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!