How to convert consecutive numbers in NaN?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Fabian Moreno
el 12 de Mayo de 2021
Comentada: Star Strider
el 12 de Mayo de 2021
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.
0 comentarios
Respuesta aceptada
Star Strider
el 12 de Mayo de 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'
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
I made it as robust as I could.
6 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Multidimensional Arrays en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!