How to substitue NaN cells in a column (or matrix) with the previous valid number?
1 回表示 (過去 30 日間)
古いコメントを表示
Hi guys, pretty easy question i guess...
I have a very big matrix full of NaN values, thousands of them in each column. I need to replace them with the fist oldest value available..
Let's say that i have a column like this:
1
2
4
NaN
2
In this case i should replace NaN with 2. I have some complexities, for example i may not have a rectangular matrix and i could have some nan at the end of the column... in this case i should replace the nan with the first value "up".. Example:
1
3
2
NaN
NaN
In this case the NaN must become both 2.
I attach an example of a little .mat file ready to make some tries.
Thank you so much for the help.
0 件のコメント
採用された回答
Joseph Cheng
2014 年 3 月 18 日
編集済み: Joseph Cheng
2014 年 3 月 18 日
This is the quickest way I was able to come up with. Not very elegant or probably the most optimal way but here is it. I would start by finding the last non-NaN value and having it substitute the last entry in the column. This ensures that the very last entry is a number. Then replaces each NaN value with the following number until there is no more NaN values left in that column. Then moves to the next column.
iexample = Example;
for i =1:4
temp = iexample(:,i);
A = isnan(temp);
A = find(A==0);
temp(end) = temp(A(end));
while sum(isnan(temp))~=0
B = isnan(temp);
B = find(B==1);
temp(B)=temp(B+1);
end
iexample(:,i)=temp;
end
I was hoping i would be able to come up with a scheme instead of the while loop by substituting consecutive NaN by the first valid number after the NaN. But haven't figure that one out yet.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Function Creation についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!