filling nans between two values
Show older comments
Hi,
I have matrices in which I want to fill the nans with the last available number. for example: A=[ 1 nan;nan 3;nan 2;4 nan;nan nan]; I want it to become A=[ 1 nan;1 3;1 2;4 2;4 2]; Is there an easy way of replacing these nans without running a loop. I have large matrices and I need to do this frequently. So,I am wondering if an easy command exists.
Accepted Answer
More Answers (1)
Oleg Komarov
on 1 Sep 2011
EDITED
Polished and robustified version of Andrei's algorithm:
A = [NaN NaN
1 NaN
NaN 2
4 0
NaN NaN];
% Index non NaNs and store elements
idxEl = ~isnan(A);
nnNaN = [0; A(idxEl)];
% Positions to non NaN elements
pos = cumsum(idxEl);
% Detect initial NaNs
idxNaN = pos == 0;
% Adust pos with offset for number of non NaN elements in each column
offs = cumsum([1 sum(idxEl(:,1:end-1))]);
pos = bsxfun(@plus,pos,offs);
% Output
B = nnNaN(pos);
% Place back initial NaNs
B(idxNaN) = NaN
2 Comments
Andrei Bobrov
on 1 Sep 2011
Hi Oleg! Thanks a lot for your vote and cod.
I too corrected my last variant
+1.
Oleg Komarov
on 1 Sep 2011
Thanks but all the merit goes to you. No idea, no risk for small corrections :).
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!