If you want to replace a scalar based on a 3D array, you either need 3 nanmean calls:
nanmean(nanmean(nanmean(data(i-1:i+1, j-1:j+1, k-1:k+1))))
with i-1:i+1, instead of i-2:i+2. This would be easier:
if isnan(data(i,j,k)) % "== 1" is not needed tmp = data(i-1:i+1, j-1:j+1, k-1:k+1); % 3D block data(i,j,k) = nanmean(tmp(:)); % Make it a vector end
But this is a 3x3x3 neighborhood with 27 elements, not 8. I assume you mean:
if isnan(data(i,j,k)) % "== 1" is not needed tmp1 = data(i-1:i+1, j, k); tmp2 = data(i:i, j-1:j+1, k); tmp3 = data(i, j, k-1:k+1); tmp = [tmp1(:); tmp2(:); tmp3(:)]; % Create a vector data(i,j,k) = nanmean(tmp); end
Because the center point data(i,j,k) is included 3 times, but ignored by nanmean, you have 6 neighbors now, not 8.
So please explain again, what you exactly want.
means = conv2(YourMatrix, [1 1 1;1 0 1;1 1 1]/8,'same') ; mask = isnan(YourMatrix); YourMatrix(mask) = means(mask);
No loops needed.
Note: you would need a little adjustment to handle a nan on the edge of the matrix, to calculate the means properly.