How to convert consecutive numbers in NaN?

1 view (last 30 days)
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.

Accepted Answer

Star Strider
Star Strider on 12 May 2021
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 Comments
Fabian Moreno
Fabian Moreno on 12 May 2021
Thanks a lot, Star Strider! I got it much better. Amazing! Thank you.

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!