How to speed up my code containing several for loops

1 次查看(过去 30 天)
I have written a code which aims to compute and plot a function called Qd(f), with f is the frequency vector. This function is given by the following expression:
Eq_Qd_corrected.png
Where PN is a Pseudo random vector of 1’s and -1’s of length L. This vector is simply generated with an independent function. Here, I will give directly the vector PN.
For practical reasons k abd k' are integers in the interval [-5*L, 5*L].
f is a frequency vector in the form of with n integer. Depending on problem constraints, PN can takes several lengths.
I have written the code for Qd(f) for L=31 using several for loops. The code works correctly but it takes several hours to display the result. I want to run my code for different length of PN, L=31, 63, 127, 255, 511, 1024, 2047 and 4095. The problem arises when L takes much important values, for example L=511 and higher. The code takes much more time (more than one day without result !).
My goal is to vectorize the inner loops in order to reduce the time of execution of the code. Below is the PN vector of length 31:
PN=[ 1 1 1 1 1 -1 -1 1 1 -1 1 -1 -1 1 -1 -1 -1 -1 1 -1 1 -1 1 1 1 -1 1 1 -1 -1 -1];
I would really appreciate any kind of help :)
Thank you in advance.
  4 个评论
darova
darova 2019-11-4
You have to handle 25*L^4 number of operations. I'm even afraid to count what number it is
For L=1000 number is 25e12 (number of operations). So i'm not suprised that it takes a lot of time
  • I works with longer sequences Matlab returns the error “Help memory”
I don't know if it can be vectorised as MATLAB tries to preallocate all those numbers in memory
Daly
Daly 2019-11-6
Thank you Darova for your response.
I am trying to find another solution to my problem. As you said the number of operations and the size of matrices are very important!

请先登录,再进行评论。

采纳的回答

Guillaume
Guillaume 2019-11-4
You can easily vectorise part of the inner sum computation:
%precompute before any loop:
[i, iprime] = ndgrid(1:L);
PNprod = PN(i) .* PN(iprime);
%... inside the k and k' loop:
innersum = sum(PNprod .* exp(-j*2*pi/L * (k*i + kprime*iprime)), 'all'); %'all' option requires 2018b or later
Whether or not that will help, I'm not sure. The outer k and k' loops are probably the ones that slow down everything due to the shear number of iterations.
  1 个评论
Daly
Daly 2019-11-6
Thank you Guillaume for your answer.
Unfortunately I actually work with MATLAB R2016b, but I will upgrade to the latest version as soon as possible.
Thanks for your help.

请先登录,再进行评论。

更多回答(0 个)

产品

Community Treasure Hunt

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

Start Hunting!

Translated by