How to do this more efficiently

2 views (last 30 days)
S. David
S. David on 24 May 2014
Commented: S. David on 7 Jun 2014
I have this piece of code in MATLAB:
for kk=0:N-1
for mm=0:N-1
for pp=1:Np
for qq=1:Np
if ((kk*Ts+tau(pp)))<=(mm*Ts+tau(qq))) && ((kk+1)*Ts+tau(pp))>(mm*Ts+tau(qq)))
which obviously is not very efficient. How can I re-write it more efficiently?
S. David
S. David on 25 May 2014
I attached the formula. g(t) in it is a rectangular pulse of magnitude one over the period [0,Ts).

Sign in to comment.

Accepted Answer

Roger Stafford
Roger Stafford on 26 May 2014
It isn't necessary to do the inequality test for every possible pair of kk and mm values. Since kk and mm are integers and Ts must surely be a positive number, your pair of inequalities is logically equivalent to
kk-mm == d
where d = floor((tau(qq)-tau(pp))/Ts). Therefore you can simply add the appropriate vectors along corresponding diagonals of F. For large N, doing it this way should save quite a bit of computation time.
for pp=1:Np
for qq=1:Np
d = floor((tau(qq)-tau(pp))/Ts);
kk = max(d,0):min(N-1,N-1+d);
mm = kk-d;
ix = d+1+(N+1)*mm;
F(ix) = F(ix)+conj(H(pp))*H(qq)*theta.*exp(1i*pi*fc*theta).*sinc(fc*theta);

Sign in to comment.

More Answers (1)

the cyclist
the cyclist on 24 May 2014
Especially if N is large, you might get a huge speedup if you preallocate the memory for F_SR_MR. Put the line
F_SR_MR = zeros(N,N);
ahead of the loops.

Community Treasure Hunt

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

Start Hunting!

Translated by