how to replace a sequence of specific length of NaNs?

1 view (last 30 days)
Hello,
Please help me with the following:
Consider vector
A=[2.15,NaN,NaN,1.14,NaN,NaN,0.59,NaN,NaN,0.14,NaN,NaN,0,NaN,NaN,NaN,NaN,0.08,NaN,NaN,0.39];
How can replace all the NaN sequences that are not of length=2 (i.e. not equal with the rest) with another value, e.g. with 0;
In the above example all the sequences that need to be replaced are of length = 4.
Thanks,
Pavlos

Accepted Answer

Walter Roberson
Walter Roberson on 28 Nov 2016
replacement_value = 0;
mask = [false; isnan(A(:)); false].';
nan_start = strfind(mask, [0 1]);
nan_end = strfind(mask, [1 0]);
not_len_2_idx = find( (nan_end - nan_start) ~= 2 );
Anew = A;
for K = not_len_2_idx
Anew( nan_start(K) : nan_end(K)-1 ) = replacement_value;
end

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!