MATLAB: How to replace zero elements with the mean of the closest previous and following values

matrixmeanzeroelements

for example, given matrix A:
A=[2 0 3 -1 6; -1 -2 3 5 0; 2 3 4 -1 7; 5 1 0 0 4; 0 1 5 0 -2];
I want to obtain this:
A=[2 2.5 3 -1 6; -1 -2 3 5 4; 2 3 4 -1 7; 5 1 2.5 2.5 4; 3 1 5 1.5 -2]
if zero element hasn't previous elements I want the mean between the two following elements
if zero element hasn't following elements I want the mean between the two previous elements
thanks

Best Answer

The code below doesn't average the non-zero above and below for each row, but gets the closest non-zero, with a bias towards the later values.
A=[2 0 3 -1 6; -1 -2 3 5 0; 2 3 4 -1 7; 5 1 0 0 4; 0 1 5 0 -2];
for row=1:size(A,1)
zeropos=A(row,:)==0;
if any(zeropos)
zeropos=find(zeropos);
non_zero=1:size(A,2);non_zero(zeropos)=[];
%Use implicit expansion to replicate for multiple zeros, and
%subtract a small value to force [5 1 0 0 4] to do (1+4)/2
[~,idx]=sort(abs(non_zero'-zeropos-.1));
idx=non_zero(idx(1:2,:));
if size(idx,1)==1,idx=idx';end%flip if only 1 zero
A(row,zeropos)=(A(row,idx(1,:))+A(row,idx(2,:)))/2;
end
end
%check
B=[2 2.5 3 -1 6; -1 -2 3 5 4; 2 3 4 -1 7; 5 1 2.5 2.5 4; 3 1 5 1.5 -2];
IsCorrect=~any(abs(A(:)-B(:))>2*eps)