Alternative way for nested for loops and if statements
4 次查看(过去 30 天)
显示 更早的评论
Hi everyone,
I am looking an alternative way for the algorithm that is mentioned below. There are nested for loops and multiple if statements.
I would like to run it faster, do you have any opinion how to do that ?
Thanks in advance.
for i = 1: totalCount
for j= 1: totalCount2
if (telArray(i,1) ~= telArray(j,1))
firstTel = find ( telArray(i,1) == sortedArray(:,3) ,1 );
[r] = find(heuristic(:,firstTel)~= 0);
placeOfFirst = r(1,1);
secondTel = find ( telArray(j,1) == sortedArray(:,3) ,1 );
[r] = find(heuristic(:,secondTel )~= 0);
placeOfSecond = r(1,1);
idx = placeOfFirst:repRate:macroPeriod;
sum1= sum(basePeriod(idx,2));
idx = placeOfSecond:repRate:macroPeriod;
sum2= sum(basePeriod(idx,2));
if( ( sum1> sum2+ 10 ) && (sortedArray (firstTel,1) > (sortedArray (secondTel , 1) + 1) ) )
firstDifference = sum1- sum2
sum1= sum1 + (macroPeriod / repRate) * ( sortedArray (secondTel ,1) - sortedArray (firstTel,1) );
sum2= sum2- (macroPeriod / repRate) * ( sortedArray (secondTel ,1) - sortedArray (firstTel,1) );
secondDifference = abs(sum1 - sum2);
if ( secondDifference < (firstDifference - 5) )
x = firstBP:repRate:macroPeriod;
basePeriod(x, 2) = basePeriod(x, 2) + sortedArray (secondTel ,1) - sortedArray (firstTel,1);
y = secondBP:repRate:macroPeriod;
basePeriod(y, 2) = basePeriod(y, 2) + sortedArray (firstTel,1) - sortedArray (secondTel ,1);
end
end
end
end
end
5 个评论
Steven Lord
2019-12-3
Taking a step back, can you explain in words not code the goal of this script? What is it supposed to do? There may be a function or a combination of a few functions that can achieve your goal more efficiently and/or be clearer to understand.
回答(1 个)
J. Alex Lee
2019-12-3
For nested loops you can keep as much outside of the inner loop as possible, in this case the search for placeOfFirst looks like it can be outside the inner loop?
At first glance it doesn't seem you can really get away from the nested structure, though maybe there is...
But it also looks like you may be spending a lot of time on redundant "find()" statements. It looks like you could pre-find the indices rather than find-ing each loop (for the inner find)
Not really an optimization, but to avoid nested if's this case, you can test for opposite of what you want and continue, since you don't have other bits of code happening after the if's
for i = size(telArray,1):-1:1
idx = find ( telArray(i,1) == sortedArray(:,3) ,1 );
placeof_a(i,1) = find(heuristic(:,idx)~=0,1);
end
for i = 1: totalCount
for j= 1: totalCount2
if telArray(i,1) == telArray(j,1)
continue
end
placeOfFirst = placeof_a(i);
placeOfSecond = placeof_a(j);
% ...
end
end
Does this work?
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!