Turning 1s to 0s in a logical vector when element distance between 1s is below threshold

조회 수: 4 (최근 30일)
Hello,
I have a logical vector of 1.5 million elements. I need to look through the elements in the vector, and whenever I find a 1, I need to turn any potential subsequent 1s in the next N elements into 0s. While this would be easy to implement with a for loop, I'm struggling to figure out a more efficient way to do it.
Example:
If [ 1 1 0 0 0 0 1 0 1 0 0 0 1 ] is my vector, and my N threshold is 5, I want to turn that vector into [ 1 0 0 0 0 0 1 0 0 0 0 0 1 ].
Thank you in advance.
  댓글 수: 2
Chien-Han Su
Chien-Han Su 2021년 8월 3일
How about using find() to get indices of all trues, get distance from those indices by subtraction and turn true to false for those distance bellow threshold?
Len Jacob
Len Jacob 2021년 8월 3일
This is a good starting point but I'm running into one issue--if I run something like this:
test = [ 1 1 0 0 0 0 1 0 1 0 0 0 1 ];
diff(find(test))
ans =
1 5 2 4
I would end up removing the last 1, but in practice I actually want to keep it since the 1 before that will be getting removed first. To clarify, since I want to be moving through the vector from left to right (i.e. moving forward in time), the distance between 1s will change as I flip them to 0, and I need to accommodate that.

댓글을 달려면 로그인하십시오.

채택된 답변

Jonas
Jonas 2021년 8월 4일

you can try the follwing, but i don't know if it is faster

H = [ 1 1 0 0 0 0 1 0 1 0 0 0 1 ];
eraseNAfter=5;
Hstr=num2str(H);
out=regexprep(Hstr,['1' repmat('.',[1 3*eraseNAfter])],['1' repmat('  0',[1 eraseNAfter])]);
asDouble=str2mat(out)

i am also sure the regexp could be written nicer

  댓글 수: 2
Len Jacob
Len Jacob 2021년 8월 4일
편집: Len Jacob 2021년 8월 4일
This was fast enough, thanks!
EDIT: Heads up that this fails to convert 1s at the end of your vector depending on vector size and threshold size. Not an issue for my application but something to keep in mind for others who are reading this and might want to use this implementation for something else.
Jonas
Jonas 2021년 8월 4일

that's true, fast solition would be padding the array and removing the padded elements at the end

H = [ 1 1 0 0 0 0 1 0 1 0 0 0 1 1];
eraseNAfter=5;
H=[H repmat(0,[1 eraseNAfter])];
Hstr=num2str(H);
out=regexprep(Hstr,['1' repmat('.',[1 3*eraseNAfter])],['1' repmat(' 0',[1 eraseNAfter])]);
asDouble=str2mat(out);
asDouble((end-eraseNAfter+1):end)=[]

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by