MATLAB: Select nearest non zero value in column

matrixnearest

Hi, I have a matrix of which the last column consists mainly of zeros and an occasionally non zero value. In a For loop I use each loop the next row for calculations, but for the last column I want to select the closest non zero value in that column. How should I do that? Thanks in advance!

Best Answer

b = [0; 0; 0; 2; 0; 0; 0; 0; 0; 3; 0]
nearestfun = @(b) interp1(find(b),b(b~=0),(1:length(b))','nearest','extrap');
closest = 0.5*(nearestfun(b) + flip(nearestfun(flip(b))))