MATLAB: How to interpolate NaN values

for loopif statementmatlab functionmatrixmatrix manipulation

I have Matrix A as:
A = [4 5 9 Nan 8 3 4 4
3 5 9 7 8 3 4 4
4 4 5 8 6 5 4 4
4 5 9 Nan 8 3 4 4
3 5 1 Nan 5 4 9 1
7 2 2 8 5 5 6 1
3 4 1 2 5 4 9 8
3 5 1 4 1 1 1 9
3 4 5 2 3 4 6 6
3 4 5 Nan 3 4 6 6];
There are some NaN values in column 4. I want to find similar rows in matrix A and give relevant value of their column 4 to those NaN cells. In case if all cells in a row aren't matching with the row of Nan, find the most matchable (perhaps weighting option).
Results can be similar to B:
B = [4 5 9 7 8 3 4 4
3 5 9 7 8 3 4 4
4 4 5 8 6 5 4 4
4 5 9 7 8 3 4 4
3 5 1 2 5 4 9 1
7 2 2 8 5 5 6 1
3 4 1 2 5 4 9 8
3 5 1 4 1 1 1 9
3 4 5 2 3 4 6 6
3 4 5 2 3 4 6 6];
% first and fourth rows Nan values got value 7 from second row because of most similarity % fifth row Nan value got value 2 from the seventh row because of most similarity % tenth row Nan value got value 2 from the ninth row because of exact similarity

Best Answer

>> X = isnan(A(:,4));
>> C = [1:3,5:8];
>> D = sum(bsxfun(@minus,permute(A(~X,C),[1,3,2]),permute(A(X,C),[3,1,2])).^2,3);
>> [~,Y] = min(D,[],1);
>> Z = find(~X);
>> A(X,4) = A(Z(Y),4)
A =
4 5 9 7 8 3 4 4
3 5 9 7 8 3 4 4
4 4 5 8 6 5 4 4
4 5 9 7 8 3 4 4
3 5 1 8 5 4 9 1
7 2 2 8 5 5 6 1
3 4 1 2 5 4 9 8
3 5 1 4 1 1 1 9
3 4 5 2 3 4 6 6
3 4 5 2 3 4 6 6
>> Z(Y) % the rows used
ans =
2
2
6
9