Fill NaNs in array with last value

조회 수: 7 (최근 30일)
Leah
Leah 2013년 10월 1일
편집: Shruti Verma 2017년 8월 6일
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
Sean de Wolski 2013년 10월 1일
편집: Sean de Wolski 2013년 10월 1일
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
  댓글 수: 3
Image Analyst
Image Analyst 2013년 10월 1일
Clever!
Leah
Leah 2013년 10월 1일
ya wow... impressive. thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2013년 10월 1일
편집: Jan 2013년 10월 1일
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
Khaing Zin Htwe
Khaing Zin Htwe 2016년 5월 10일
if true
% data = [321 nan() nan() nan() nan() 55 ;nan() nan() nan() 22 nan() 21; nan() nan() 3 66 5 8];
end
I want to fill with integer zeros to NaN values,sir. How can I do it? please help me.
Shruti Verma
Shruti Verma 2017년 8월 6일
편집: Shruti Verma 2017년 8월 6일
This should do it :)
data(isnan(data)) = 0;

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 NaNs에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by