How to change a Data Series contained with Repeated NaNs to become other sequence of NaNs?
1 view (last 30 days)
Show older comments
Hi, community
I want to ask something that is still difficult for me to generate the code in Matlab. The data is simple, that is :
A = [NaN, NaN, 0, 0, 0, NaN, NaN, 0, 0, 0, 0, 0, NaN, NaN, 0, NaN, NaN];
And i just want to re-create the data A, with double NaN unique data, to become :
B = [NaN, 0, 0, 0, 0, NaN, 0, 0, 0, 0, 0, 0, NaN, 0, NaN, 0];
And so on for every double NaN of Data A were changed to become Data B with a single NaN unique data?
Its so difficult for me to create such a code for data A to become data B.... Anyone in Community culd help me in solving my problem here? Thank you so much, im so grateful if someone can help me out.... /.\ /.\ /.\
2 Comments
Accepted Answer
Stephen23
on 31 Dec 2021
A = [NaN, NaN, NaN, 0, 0, NaN, NaN, 0, 0, 0, 0, 0, NaN, NaN, NaN, NaN, NaN]
X = diff([isnan(A),false])<0;
A(X) = 0
3 Comments
More Answers (2)
Chunru
on 31 Dec 2021
Edited: Chunru
on 31 Dec 2021
A = [NaN, NaN, 0, 0, 0, NaN, NaN, 0, 0, 0, 0, 0, NaN, NaN, 0, NaN, NaN];
idx = isnan(A);
% any repeated nan will be replaced with 0
A(idx == 1 & diff([0 idx]) == 0) = 0
% replace last nan in sequence with 0
A = [NaN, NaN, NaN, 0, 0, NaN, NaN, 0, 0, 0, 0, 0, NaN, NaN, NaN, NaN, NaN];
idx = isnan(A);
A(diff([idx 0])==-1) = 0
Walter Roberson
on 31 Dec 2021
3 tests to be sure the boundary tests are handled correctly -- ending in double nan, ending in single nan, ending in no nan.
Should probably have similar tests about starting with variable number of nan.
%actual work
DN = @(V) V(~isnan(V) | [~isnan(V(2:end)), true]);
%rest is testing
A = [NaN, NaN, 3, 5, 7, NaN, NaN, 2, 4, 6, 8, 10, NaN, NaN, -3, NaN, NaN]
B = DN(A)
A2 = A(1:end-1)
B2 = DN(A2)
A3 = A(1:end-2)
B3 = DN(A3)
3 Comments
See Also
Categories
Find more on Time Series Events 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!