MATLAB: Efficiency fix

efficiency

Hi, another efficiency fix needed. this one runs over 20 second everytime. would be a big help if that nested loop could be shortened somehow.Thanks!
counter3 = 1;
for n = 1: length(mymatrix2(1,:))
for p = 1:length(mymatrix2(1,:))
if abs (mymatrix2(1,n) - mymatrix2(1,p)) == 1;
if mymatrix2(2,n) >= mymatrix2(2,p) ;
if ismember ( mymatrix(1,n), replacewith) == false
replacewith(counter3) = mymatrix2(1, n);
end
elseif mymatrix2(2,p) >=mymatrix2(2,n);
if ismember (mymatrix(1,p), replacewith) == false
replacewith(counter3) = mymatrix2(1,p);
end
end
counter3 = counter3 +1;
end
end
end

Best Answer

Some simplifications at first:
counter3 = 1;
len = size(mymatrix2, 2);
for n = 1:len
a = mymatrix(1, n);
for p = 1:len
b = mymatrix2(1,p);
if abs(a - b) == 1
if mymatrix2(2,n) >= mymatrix2(2,p)
if ~any(a == replacewith)
replacewith(counter3) = a;
end
elseif mymatrix2(2,p) >= mymatrix2(2,n);
if ~any(b == replacewith)
replacewith(counter3) = b;
end
end
counter3 = counter3 + 1;
end
end
end
But I'm sure this profits from vectorization. Please post meaningful test data - a RAND is preferred.