Let
M = [0 0 3
3 0 0
0 3 0
0 0 0
3 0 3
0 3 0
3 0 0
0 0 0
2 3 3
0 0 0
3 0 0
0 1 0
0 0 0
3 3 3
0 0 0];
[r,c] = size(M);
m = M;
m(m == 0) = nan;
lo = fillmissing(m,'previous') == 3 & fillmissing(m,'next') == 3 & isnan(m);
ii = cumsum([zeros(1,c);diff(lo)>0]).*lo;
[~,jj] = ndgrid(1:r,1:c);
p = accumarray([ii(:)+1,jj(:)],1);
p = p(2:end,:);
a = repmat([3;4*ones(max(ii(:))-1,1)],1,c);
a(2:end,:) = a(2:end,:) - (p(2:end,:) == 1);
M(lo) = repelem(a(:),p(:));
Best Answer