Speed up a for loop in my programme?

1 Ansicht (letzte 30 Tage)
Alberto Paniate
Alberto Paniate am 29 Jul. 2021
Hi, one of the part of my programme contains this piece of code:
size2=2500;
gran=3;
A=ones(size2,size2);
for k=1:gran:(size2-gran)
for j=1:gran:(size2-gran)
X=rand*2*pi-pi;
for h=1:gran
for l=1:gran
A(k+l-1,j+h-1) = A(k+l-1,j+h-1) *exp(+1i*X); %phase in the square gran x gran
end
end
end
end
My pc runs this code in 0.60 seconds but I would like to know if it is possible to speed up this process.
I have already looked similar questions like:
but I don't know if I can apply to my problem
  2 Kommentare
Yongjian Feng
Yongjian Feng am 29 Jul. 2021
Can this be written as matrix operations? If so, then use the corresponding matlab matrix operation. Then Matlab might be able to optimize the process for you.
Alberto Paniate
Alberto Paniate am 29 Jul. 2021
I don't know, I have to create a matrix X of random numbers each square of sides gran x gran. In these squares the randoms numbers are equal

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Eike Blechschmidt
Eike Blechschmidt am 30 Jul. 2021
If I understood you right this could do the trick and is about 2.5x faster on my machine.
tic();
X=rand(size2*size2,1)*2*pi-pi;
[row,col] = ind2sub([size2, size2],1:size2*size2);
blockRow = ceil(row/gran);
blockCol = ceil(col/gran);
idx = sub2ind([size2/gran, size2/gran], blockRow, blockCol);
A = ones(size2, size2);
A(1:size2*size2) = exp(+1i*X(idx));
toc();
Important to not is that size2 needs to be a multiple of gran to for this solution to work.

Kategorien

Mehr zu Systems of Nonlinear Equations finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by