# Fill NaNs in array with last value

13 views (last 30 days)
Leah on 1 Oct 2013
Edited: Shruti Verma on 6 Aug 2017
Hi all, thanks for your help. I have a double array and I want to fill NaN values with the last value.
Example:
[321 nan() nan() nan() nan() 55 nan() nan() nan() 22 nan() 21 nan() nan()]
desired result
[321 321 321 321 321 55 55 55 55 22 22 21 21 21]
Also I want to do this same thing with a cell array of strings with blanks instead of NaN. I'm trying to avoid ugly for loops here. This seems familiar... maybe it was a cody question I couldn't solve. Thanks again.

Sean de Wolski on 1 Oct 2013
Edited: Sean de Wolski on 1 Oct 2013
You still have to figure out what to do if the first value is nan.
v = [321 nan() nan() nan() nan() 55 nan() nan() nan() 22 nan() 21 nan() nan()];
idx = (~isnan(v)); %non nans
vr = v(idx); %v non nan
v2 = vr(cumsum(idx)) %use cumsum to build index into vr
Leah on 1 Oct 2013
ya wow... impressive. thank you!

Jan on 1 Oct 2013
Edited: Jan on 1 Oct 2013
What's wrong with FOR loops?
data = [321 nan() nan() nan() nan() 55 nan() nan() nan() 22 nan() 21 nan() nan()];
for k = find(isnan(data))
data(k) = data(k - 1);
end
But here a vectorized version:
notNaN = ~isnan(data);
index = find(notNaN);
fillup = zeros(size(data));
fillup(notNaN) = index - [0, diff(index)];
result = data(cumsum(fillup));
Much uglier than the loop. I cannot test this currently. You have to care for initial NaNs in addition. And Sean's solution is nicer.
##### 2 CommentsShowHide 1 older comment
Shruti Verma on 6 Aug 2017
This should do it :)
data(isnan(data)) = 0;