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

5 visualizaciones (últimos 30 días)
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 comentarios
Matt J
Matt J el 21 de Oct. de 2021
Also, the dependence of 't' and 'adj' on the loop variables is not shown.
Jaya
Jaya el 21 de Oct. de 2021
Editada: Jaya el 21 de Oct. de 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

Iniciar sesión para comentar.

Respuesta aceptada

Cris LaPierre
Cris LaPierre el 21 de Oct. de 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 comentario
Jaya
Jaya el 22 de Oct. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by