Converting elements which repeat more than 10 times to 0

조회 수: 1 (최근 30일)
Mate 2u
Mate 2u 2013년 7월 4일
Hi there, I have an array (4048x1) full of 1s and -1s. I want change it so that, if there are more than 10 consecutive 1s or 10 consecutive -1s, then the rest of the consecutive elements after the 10 will become 0 (zeros).
Ie, if we have 1 -1 1 1 -1 -1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 -1 1
we would want 1 -1 1 1 -1 -1 1 1 1 1 1 1 1 1 1 1 0 0 -1 1 -1 1
Thanks
  댓글 수: 1
Sivakumaran Chandrasekaran
Sivakumaran Chandrasekaran 2013년 7월 4일
i think u can use sum command for 10 ones... if sum==10 then '0' should be placed.

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

채택된 답변

Ken Atwell
Ken Atwell 2013년 7월 4일
I would love to see a vectorized way to do this, but using a loop:
x=[1 -1 1 1 -1 -1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 -1 1];
zeroX = false(size(x));
for i =11:numel(x)
xsum = sum(x(i-10:i));
if xsum>10 || xsum <-10
zeroX(i) = true;
end
end
x(zeroX) = 0

추가 답변 (1개)

Tom
Tom 2013년 7월 4일
A = [1 -1 1 1 -1 -1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 -1 1];
Correct = [1 -1 1 1 -1 -1 1 1 1 1 1 1 1 1 1 1 0 0 -1 1 -1 1];
D = [0 diff(A)]/2; %find split points
C = cumsum(abs(D))+1; %create accumarray subs
M = accumarray(C',A,[], @(x) {x'.*(1:length(x) <= 10)}); %split each section into a cell array and set > 10 to 0
B = [M{:}]; %merge
isequal(Correct,B)
  댓글 수: 1
Ken Atwell
Ken Atwell 2013년 7월 5일
Ah, the magic of accumarray, thanks for sharing.
In this case, the loop is probably the "better choice", as it runs in under half the time and would use far less memory (no cell arrays)

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

카테고리

Help CenterFile Exchange에서 Data Types에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by