matrix nan
2 ビュー (過去 30 日間)
古いコメントを表示
hi, i have multiple nans in my 1000x1 matrix. I want to replace the nans with the average of the number above and below it......please note if there are more than 1 nans in a row it should take average of the numbers above and below it.
FOR EXAMPLE. My Array:
2
3
nan
5
nan
nan
9
3
2
........desired output:
2
3
4
5
7
7
9
3
2
0 件のコメント
回答 (3 件)
Nirmal
2012 年 6 月 20 日
a=[2 3 NaN 5 NaN NaN 9 3 2];
[m,n]=size(a);
b=isnan(a);
for j=1:n
if b(j)==1
li=j-1;
while b(li)==1
li=li-1;
end
ui=j+1;
while b(ui)==1
ui=ui+1;
end
avg=(a(li)+a(ui))/2;
a(j)=avg;
end
end
The code however doesnt handle the boundary case. Its just couple of if checks.
0 件のコメント
Andrei Bobrov
2012 年 6 月 20 日
data = [2
3
nan
5
nan
nan
9
3
2];
a1 = isnan(data);
vle = mean(data([strfind(a1(:)',[0 1]);strfind(a1(:)',[1 0])+1]));
id = bwlabel(a1);
data(a1) = vle(id(id~=0));
0 件のコメント
Image Analyst
2012 年 6 月 21 日
Here's a method that I think is pretty easy to understand and is only 4 lines long.
% Generate sample data.
array2D = randi(5, [20 20])
nanIndices = randperm(numel(array2D))
% Take first 50 of them nan's and assign to the array
array2D(nanIndices(1:50)) = nan
% Now we have our sample data.
% Now we are ready to begin. Here are the 4 lines of code:
% Find the nan's
nanIndices = isnan(array2D);
% Replace nan's by zeros
array2D(nanIndices) = 0
% Get the average matrix in a vertical 3x1 window.
verticalAverageMatrix = conv2(array2D, [1;1;1], 'same') / 2
% Replace nan's with the average
array2D(nanIndices) = verticalAverageMatrix(nanIndices)
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で NaNs についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!