How to make my code faster when working with for loop code & large array indexing?
5 ビュー (過去 30 日間)
古いコメントを表示
I have a demands vector that gives output as below. It means I have 4992 demands at first time instant and then 5025,etc.
% demands= poissrnd(5000,1,4)
demands =
4992 5025 5009 5108
And I want to initialize these many number of demands at each time instant. For e.g. at d=1, I create 4992 vectors & at d=2, I create 5025 vectors, etc. Each vector is initialized with a certain values of source, destination, req_slots and a threshold value. This is shown below.
for d=1:numel(demands) %at each element of demands shown above
for dd=1:demands(d) % When d=1, dd=1:4992. And when d=2,dd=1:5025
[source(dd),destin(dd),required_slots(dd),osnr_th(dd)]=initialize_demand(t,adj) %to initialize each dd numbered demand
end %the initialize_demand fn is not shown here
end
This code works perfectly fine. But it takes a lot of time even with this 5000 value ranges. I may have to increase it to 1 million in later stages. So, is there a smart way of doing this? Like using just one loop or even some other data structure to initialize quickly?
4 件のコメント
採用された回答
Cris LaPierre
2021 年 10 月 21 日
A couple thoughts.
The biggest speedup will happen by suppressing your outputs. Put a semi-colon after every line. Doing that, your code ran in 17 seconds.
Another thought. If everything is working pefectiy fine, then you can get rid of the outer for loop. Based on the indexing used, your final loop will overwrite most if not all elements in your output variables using the final value in demands (d=numel(demands)). Doing this reduce run time to 3 seconds.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Data Distribution Plots についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!