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!