Efficiency fix

2 views (last 30 days)
Andy
Andy on 13 Jan 2012
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
  1 Comment
Walter Roberson
Walter Roberson on 13 Jan 2012
Andy, I had to edit a fair bit to make the code readable. Please be especially careful about trailing blanks on the line: if they fall in just the wrong place then things might look right as you enter the code in, but look bad in the finished message. Best is not to have trailing blanks.
I left in the semi-colon you have at the end of an "if" and an "elseif" line. Those semi-colon are not necessary.

Sign in to comment.

Accepted Answer

Jan
Jan on 14 Jan 2012
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.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!