Add missing numbers of 0's and 1's in an array
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Walter Roberson
2021-9-26
编辑:Walter Roberson
2021-9-26
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.
回答(2 个)
Walter Roberson
2021-9-26
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 个评论
Akira Agata
2021-9-26
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Software Development Tools 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!