matrix nan
1 次查看(过去 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!