MATLAB Answers

# How to convert consecutive numbers in NaN?

조회 수: 4(최근 30일)
Fabian Moreno 2021년 5월 12일
댓글: Star Strider 2021년 5월 12일
Hi there, I have a matrix (8760x18) with random numbers. the values have valid zeros and invalid zeros. The invalid zeros are continually presented, I mean postion (12 13 14 15 16 . . . 21) or any position between 1 and 8760. The valid zeros have randomly positions, I mean position (9 has zero value) but the position before and after are numbers > 0. To understand better I did an example, which is varaible (y). It has 10 continually invalid zeros that I would like become NaN, but it has also valid zeros that I would like to keep. My idea is the next -> If there is more than fice consecutive zeros, become NaN, if not, leave 0's.
|-- invalid zeros--| |valid|
y= [1 2 3 5 2 6 4 8 0 5 2 0 0 0 0 0 0 0 0 0 0 1 2 5 6 9 8 74 0 0 0 32 8 4 6 1 10 2]';
I already try to do the next code, but the result is:
for i=1:length(y)
if y((i)+5,1)==0 & y((i)+4,1)==0 & y((i)+3,1)==0 & y((i)+2,1)==0 & y((i)+1,1)==0
y(i,1) = NaN;
end
end
y= [1 2 3 5 2 6 4 8 0 5 NaN NaN NaN NaN NaN NaN NaN 0 0 0 0 0 2 5 6 9 8 74 0 0 0 32 8 0 6 1 10 0];
And like the last number is zero, obviusly get an error that exceeds array bounds, but coudn't fix it.
Index in position 1 exceeds array bounds (must not exceed 38).
Error in analise_dados_mp25 (line 71)
if y((i)+5,1)==0 & y((i)+4,1)==0 & y((i)+3,1)==0 & y((i)+2,1)==0 & y((i)+1,1)==0
Thanks in advanced.

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

### 채택된 답변

Star Strider 2021년 5월 12일
Try this —
y = [1 2 3 5 2 6 4 8 0 5 2 0 0 0 0 0 0 0 0 0 0 1 2 5 6 9 8 74 0 0 0 32 8 4 6 1 10 2]';
y = [y;y;y; zeros(8,1)]; % Extend 'y'
y = 122×1
1 2 3 5 2 6 4 8 0 5
z5 = strfind(y(:)', [0 0 0 0 0]); % Start Indices Of Consecutive 'zero(1,5)'
dz5 = [1 find(diff(z5)>1)+1 numel(z5)]; % Index Differences
for k = 1:numel(dz5)-1 % Do Replacements
y(z5(dz5(k):dz5(k+1))-1) = NaN;
end
for k = 1:20:numel(y) % Check Result
row = sprintf([repmat('%d ',1,20) '\n'],y(k:min(k+19,numel(y))))
end
row =
'1 2 3 5 2 6 4 8 0 5 NaN NaN NaN NaN NaN NaN 0 0 0 0 '
row =
'0 1 2 5 6 9 8 74 0 0 0 32 8 4 6 1 10 2 1 2 '
row =
'3 5 2 6 4 8 0 5 NaN NaN NaN NaN NaN NaN 0 0 0 0 0 1 '
row =
'2 5 6 9 8 74 0 0 0 32 8 4 6 1 10 2 1 2 3 5 '
row =
'2 6 4 8 0 5 NaN NaN NaN NaN NaN NaN 0 0 0 0 0 1 2 5 '
row =
'6 9 8 74 0 0 0 32 8 4 6 1 10 NaN NaN NaN NaN 0 0 0 '
row = '0 0 '
I made it as robust as I could.
##### 댓글 수: 6표시숨기기 이전 댓글 수: 5
Star Strider 2021년 5월 12일
As always, my pleasure!

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

### Community Treasure Hunt

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

Start Hunting!