Efficiency fix

조회 수: 2 (최근 30일)
Andy
Andy 2012년 1월 13일
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
Walter Roberson
Walter Roberson 2012년 1월 13일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2012년 1월 14일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by