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

4 views (last 30 days)
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 Comments
Jaya
Jaya on 21 Oct 2021
Edited: Jaya on 21 Oct 2021
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

Sign in to comment.

Accepted Answer

Cris LaPierre
Cris LaPierre on 21 Oct 2021
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 Comment
Jaya
Jaya on 22 Oct 2021
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Data Distribution Plots in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!