Add missing numbers of 0's and 1's in an array
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Walter Roberson
el 26 de Sept. de 2021
Editada: Walter Roberson
el 26 de Sept. de 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.
Respuestas (2)
Walter Roberson
el 26 de Sept. de 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])
zend = strfind([M 1], [0 1])
zlengths = zend - zstarts + 1
ostarts = strfind([0 M], [0 1])
oends = strfind([M 0], [1 0])
olengths = oends - ostarts + 1
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
elements = zeros(1,length(runs));
elements(2:2:end) = 1;
newM = repelem(elements, 1, runs);
num2str(newM)
0 comentarios
Akira Agata
el 26 de Sept. de 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');
0 comentarios
Ver también
Categorías
Más información sobre Software Development Tools en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!