Matlab code which implements replacement algorithm