I have a a multidimensional array (49x49x49) which has NaN values scattered randomly. For each NaN, I want to replace the value with the previous non NaN value. e.g. if i had a 3 x 3 matrix 4 7 9 2 7 NaN 1 2 NaN should become 4 7 9 2 7 7 1 2 2 I have 3 dimensions [i,j,k], but it doesn't matter which dimension I move back in, so long as it is an adjacent element. Anybody have a solution to my problem? EDIT: I guess I could make several loops, find the NaNs and replace e.g i with i-1. But shouldn't there be a more efficient way in Matlab?