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 个评论
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 CenterFile Exchange 中查找有关 Data Distribution Plots 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by