replacing NaN with it previous element

1 次查看(过去 30 天)
Dear all,
I have
K={
'IT' 'ooil' 'TTT' [ 0] [4.1583]
'IT' 'ooil' 'TTT' [ 0] [4.0339]
'IT' 'ooil' 'TTT' [ 0] [3.9389]
'IT' 'ooil' 'TTT' [ 0] [3.9676]
'ITn' 'ooilb' 'TTT' [ 0] [3.9313]
[NaN] [ NaN] [NaN] [ 0] [3.9313]
'IT' 'ooil' 'TTT' [ 0] [3.8720]
'ITcv' 'ooila' 'TTT' [ 0] [3.8829]
[NaN] [ NaN] [NaN] [ 0] [3.9313]
'IT' 'ooil' 'TTT' [ 0] [3.8681]
'ITf' 'ooilg' 'TTT' [ 0] [4.3944]
[NaN] [ NaN] [NaN] [ 0] [3.9313]}
And I want to replace the NaNs in each column with its previous element of the same column
That is,
K={
'IT' 'ooil' 'TTT' [ 0] [4.1583]
'IT' 'ooil' 'TTT' [ 0] [4.0339]
'IT' 'ooil' 'TTT' [ 0] [3.9389]
'IT' 'ooil' 'TTT' [ 0] [3.9676]
'ITn' 'ooilb' 'TTT' [ 0] [3.9313]
'ITn' 'ooilb' 'TTT' [ 0] [3.9313]
'IT' 'ooil' 'TTT' [ 0] [3.8720]
'ITcv' 'ooila' 'TTT' [ 0] [3.8829]
'ITcv' 'ooila' 'TTT' [ 0] [3.9313]
'IT' 'ooil' 'TTT' [ 0] [3.8681]
'ITf' 'ooilg' 'TTT' [ 0] [4.3944]
'ITf' 'ooilg' 'TTT' [ 0] [3.9313]}
Thanks in advance

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2012-8-8
res=K,
for k=1:size(K,1);
if isnan(K{k,1});
res(k,1:3)=K(k-1,1:3);
end;
end

更多回答(2 个)

Isktaine
Isktaine 2012-8-8
编辑:Isktaine 2012-8-8
Save this function then use it on K:
function K = RemoveNaNs(K)
[rows,cols]=size(K); %Works out how many rows and columns there are
for p=1:rows
for q=1:cols
if isnan(K{p,q})==1 %If there is a NaN entry
K{p,q}=K{p-1,q}; %Replace it with the entry from the previous row.
end
end
end
end
Is this clear?
  3 个评论
John Petersen
John Petersen 2012-8-8
That wouldn't be a problem because you've already replaced the 1st nan. The only problem would be a nan in the very 1st line. Then p-1=0 and you would get an error. So p needs to start at 2 and there needs to be an initialization in case the first row has a nan.
Isktaine
Isktaine 2012-8-8
Yeah John is right. I didn't know what antonet would want the value to be if there was a NaN in the first row, so I didn't address this.
Thanks Lucas! :)

请先登录,再进行评论。


Thomas
Thomas 2012-8-8
K={
'IT' 'ooil' 'TTT' [ 0] [4.1583]
'IT' 'ooil' 'TTT' [ 0] [4.0339]
'IT' 'ooil' 'TTT' [ 0] [3.9389]
'IT' 'ooil' 'TTT' [ 0] [3.9676]
'ITn' 'ooilb' 'TTT' [ 0] [3.9313]
[NaN] [ NaN] [NaN] [ 0] [3.9313]
'IT' 'ooil' 'TTT' [ 0] [3.8720]
'ITcv' 'ooila' 'TTT' [ 0] [3.8829]
[NaN] [ NaN] [NaN] [ 0] [3.9313]
'IT' 'ooil' 'TTT' [ 0] [3.8681]
'ITf' 'ooilg' 'TTT' [ 0] [4.3944]
[NaN] [ NaN] [NaN] [ 0] [3.9313]}
% needs only 3 lines of code
A=K;
[r,c]=find(cellfun(@(V) any(isnan(V(:))), A));
K(r,c)=K(r-1,c)
  2 个评论
Isktaine
Isktaine 2012-8-8
That's certainly more brief than my code, could you explain what V is?
Thomas
Thomas 2012-8-8
@V creates an anonymous function. The cellfun documentation has more on it.. http://www.mathworks.com/help/techdoc/ref/cellfun.html

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by