Set logical array values to true if value n values ahead is true

I'm curious if anyone can find a smart/clean way (other than a for loop of doing the following). Given a logical array x:
x = logical( [0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0] );
For n = 1 I'd like: y = [0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0];
For n = 2 I'd like: y = [0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0];
etc.

댓글 수: 2

Matt Fig
Matt Fig 2012년 11월 26일
편집: Matt Fig 2012년 11월 26일
Your examples conflict with your description. Do you want to place n values in the array ahead of a 1 as your examples show, or do you want to place a single 1 ahead of n 1s, as the title implies? If the latter, do you need to place a 1 only in front of exactly n 1s, or at least n 1s?
Sorry, it is indeed the latter. I want to place n values in the array ahead of a 1. Either exactly or at least are fine b/c x will always have "isolated" 1s.

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

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 11월 26일
x = [0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0] > 0;
n = 2;
x(bsxfun(@minus,find(x),(n:-1:1)')) = true;

추가 답변 (2개)

Matt J
Matt J 2012년 11월 26일
n=2;
y=regexprep(char(x+'0'),[repmat('.',1,n),'1'], [repmat('1',1,n),'1'])-'0'
Matt J
Matt J 2012년 11월 26일
y=logical(tril(triu(ones(length(x))),n)*x(:)).'

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2012년 11월 26일

Community Treasure Hunt

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

Start Hunting!

Translated by