Removing zeros from a binary array if length of zeros is lesser than a value

3 ビュー (過去 30 日間)
Hello,
I have an array:
input = [0;0;0;0;0;0;0;1;0;1;1;1;0;0;0;0;0;0;1;1;0;0;0;0]
I would like to remove only the 0's between the 1's if the stretch of 0's is lesser than 5, between the 1's. So, for this instance, the output would look something like:
output = [0;0;0;0;0;0;0;1;1;1;1;0;0;0;0;0;0;1;1;0;0;0;0].
Any help would be appreciated.
Thanks!

採用された回答

KSSV
KSSV 2020 年 2 月 19 日
input = [0;0;0;0;0;0;0;1;0;1;1;1;0;0;0;0;0;0;1;1;0;0;0;0] ;
idx = input==1; % get the locations of 1
% split zeros and one's into cell
idr = diff(find([1;diff(idx);1]));
D = mat2cell(input,idr(:),size(input,2));
% get the lengths of each cell
L = cellfun(@length,D) ;
L(2:2:end) = NaN ; % make length of 1's NaN as it is not needed
% get the length of zeros which are less then 4
id = L<4 ;
% remove those zeros
D(id) = [] ;
% convert to matrix
output = cell2mat(D) ;
  5 件のコメント
Stephen23
Stephen23 2020 年 2 月 19 日
The RHS would need to be a scalar cell array:
D(id) = {1};
Meghana Balasubramanian
Meghana Balasubramanian 2020 年 2 月 19 日
Stephen,
Some of the cells have zeros of varying lengths. Replacing it with {1} would simply reduce the entire cell content to 1. Should I run a for loop to find and replace the zero's between the 1's using values stored in "L = cellfun(@length,D);" ?

サインインしてコメントする。

その他の回答 (1 件)

Raymond MacNeil
Raymond MacNeil 2020 年 2 月 19 日
k = [0;0;0;0;0;0;0;1;0;1;1;1;0;0;0;0;0;0;1;1;0;0;0;0];
y = regexp(num2str(k)', '(?<=[0]{5,})0*', 'split');
z = strjoin(cellfun(@(x) replace(x, '', ' '), y, 'UniformOutput', false));
out = str2num(z)';
  1 件のコメント
Raymond MacNeil
Raymond MacNeil 2020 年 2 月 19 日
編集済み: Raymond MacNeil 2020 年 2 月 19 日
Could also use regexprep. I realize I added more steps than was necessary. Also, other ways exist that don't require regexp. This just happened to be the first solution that came to mind.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by