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