How to make my code faster when working with for loop code & large array indexing?

5 ビュー (過去 30 日間)
Jaya
Jaya 2021 年 10 月 20 日
コメント済み: Jaya 2021 年 10 月 22 日
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 件のコメント
Matt J
Matt J 2021 年 10 月 21 日
Also, the dependence of 't' and 'adj' on the loop variables is not shown.
Jaya
Jaya 2021 年 10 月 21 日
編集済み: Jaya 2021 年 10 月 21 日
I thought maybe they are not important to show. But here they are. Please any comments now?
j=[ 1 1 2 2 2 3 3 4 5];
t=[ 2 6 3 5 6 5 4 5 6]; %these two are used as node numbers to make a graph.
G = addedge(G,j,t) ;
adj= full(adjacency(G)); %adj is the adjacency matrix. Is a 6*6 matrix of 1's and 0's

サインインしてコメントする。

採用された回答

Cris LaPierre
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.
  1 件のコメント
Jaya
Jaya 2021 年 10 月 22 日
Thanks a lot! I did put semi-colons later but with a different goal. And I too observed the speed up. I will work on the removal of outer loop idea too.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by