"mohamad ali " <itani.mai@hotmail.com> wrote in message <ini62s$jdc$1@fred.mathworks.com>...
> Hello there,
> I'd like some help in optimizing the script below.On large scale it's taking a lot of time.
>
> Feasible_Starting_Flow=zeros(size(segments,1),1);
> for i=1:size(SR_MinLength_Path,1)
> for j=3:size(SR_MinLength_Path,2)1
> b1=SR_MinLength_Path(i,j);
> b2=SR_MinLength_Path(i,j+1);
> for x=1:size(segments,1)
> if (segments (x,2)==b1 && segments (x,3)==b2)
> Feasible_Starting_Flow(x,1)=Feasible_Starting_Flow(x,1)+Traffic_Generated(SR_MinLength_Path(i,1),SR_MinLength_Path(i,2));
> end
> end
> end
> end
> ........
           
Your task may be performed faster if you first sort the 'segments' 2nd and 3rd columns to lexicographical (dictionary) order so as to enable faster searching through it for pairs in the rows of 'SR_MinLength_Path'. The following is one example of that. I have taken the liberty of renaming four of your arrays as:
s < segments
P < SR_MinLength_Path
T < Traffic_Generated
F < Feasible_Starting_Flow
After placing the unique, sorted pairs from s(:,2:3) into u, the pairs of each row of P(:,3:end) are subjected to a binary search in u to find possible matches. Assuming u is reasonably large this should be faster with a binary search than doing a serial search, as in your current script. In the last step the counts in F are rearranged (and possible duplications in s expanded) into the original order in s.
[u,~,ux] = unique(s(:,2:3),'rows'); % Sort unique pairs in s
n = size(u,1);
F = zeros(n,1);
m = size(P,2);
for i = 1:size(P,1); % Do this once for each row of P
a = ones(m3,1); % Initial lower bound pointer
b = (n+1)*a; % Initial upper bound
c = floor((a+b)/2); % Initial point of testing
g = P(i,3:m1).'; % g and h are pairs from current row of P
h = P(i,4:m).';
for k = 1:ceil(log2(n)) % Repeat until c can no longer change
t = g<u(c,1)  (g==u(c,1) & h<u(c,2)); % g,h pair < u(c,:) pair ?
a = t.*(ac)+c; % If false, raise the lower bound to c
b = t.*(cb)+b; % If true, lower the upper bound to c
c = floor((a+b)/2); % Set c to new midpoint
end
f = c(g==u(c,1) & h==u(c,2)); % Is there an actual match?
F = F + accumarray(f,T(P(i,1),P(i,2)),size(u,1)); % Update F from T
end
F = F(ux); % Transform F to correspond to original s order
Roger Stafford
