matrix nan

2 views (last 30 days)
Mate 2u
Mate 2u on 20 Jun 2012
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

Answers (3)

Nirmal
Nirmal on 20 Jun 2012
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.

Andrei Bobrov
Andrei Bobrov on 20 Jun 2012
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));

Image Analyst
Image Analyst on 21 Jun 2012
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)

Categories

Find more on Particle & Nuclear Physics in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!