Thank you very much for the codes. It is working quite well to my problem. However, I think there is a mistyping in the function "findrange". In this case, where we have "n=length(ns)", it should be "n=size(ns,1)".
I have suffered this kind of error using this file
Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N) to change the
limit. Be aware that exceeding your available stack space can crash MATLAB and/or your
Error in nnekf