Afficher commentaires plus anciens
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
Réponses (3)
Nirmal
le 20 Juin 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
le 20 Juin 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
le 21 Juin 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)
Catégories
En savoir plus sur Image Arithmetic dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!