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.
0 个评论
采纳的回答
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
更多回答(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!