How can i make my code run faster

3 次查看(过去 30 天)
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.

采纳的回答

Guillaume
Guillaume 2016-5-17
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 个评论
Darlington Mensah
Darlington Mensah 2016-5-17
Thanks very much.@Guillaume. Works very fast (1min as compared to the previous 7min) :).

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by