How can i make my code run faster

3 views (last 30 days)
Hi.
Is there a better way of writing a nested loop? My code Works well but it takes about 7min to completely execute.
for i=1:Z
n = 0;
for j=1:N
for k=1:M
if (Distance_Unique(i)==Distance(j,k))
n = n+1;
Residual_Sqrd(n) = Residual_Squared(j,k);
Summation_Residual_Squared(i) = sum(Residual_Sqrd);
end
end
end
Residual_Sqrd = zeros();
end
Thanks in advance. Darl.

Accepted Answer

Guillaume
Guillaume on 17 May 2016
Assuming Distance_Unique, Distance, etc. are all matrices or vectors and not functions, the two inner loops are certainly not required. I also assumed you've predeclared your Summation_Residual_Squared vector to avoid growing it in the loop.
Summation_Residual_Squared = zeros(size(Distance_Unique));
for duidx = 1:numel(Distance_Unique)
Residual_Sqrd = Residual_Squared(Distance_Unique(duidx) == Distance);
Summation_Residual_Squared(duidx) = sum(Residual_Sqrd(:));
end
  1 Comment
Darlington Mensah
Darlington Mensah on 17 May 2016
Thanks very much.@Guillaume. Works very fast (1min as compared to the previous 7min) :).

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!