필터 지우기
필터 지우기

for loops vectorization for GPU

조회 수: 3 (최근 30일)
Youngjin Jeon
Youngjin Jeon 2021년 4월 27일
답변: Ishu 2024년 4월 4일
hello people,
i want to change for loops for GPU computing.
How to effectively vectorize the loop in this code? i get stuck on this problem. help me plz :)
pnx=101;
pny=101;
pnz=101;
[pY, pX] = meshgrid(linspace(-0.5,0.5,pnx),linspace(-0.5,0.5,pny));
cnt_t=2601;
cnt_r=2601;
tr_x=linspace(-1,1,cnt_t);
tr_y=linspace(-1,1,cnt_t);
re_x=linspace(-2,2,cnt_r);
re_y=linspace(-2,2,cnt_r);
pza=linspace(0,5,101);
Obj=ones(101,101,101);
Obj(:,:,30)=Obj(:,:,30).*2;
Obj(:,:,60)=Obj(:,:,60).*3;
S= zeros(cnt_t,cnt_r);
for k = 1:cnt_t
k
for l = 1:cnt_r
S1=zeros(pnx,pny);
for z_cnt = [30 60]
A = exp(1i*sqrt( (tr_x(k)-pX).^2 + (tr_y(k)-pY).^2 + (pza(z_cnt)).^2 ) );
B = exp(1i*sqrt( (re_x(l)-pX).^2 + (re_y(l)-pY).^2 + (pza(z_cnt)).^2 ) );
S1 = S1 + Obj(:,:,z_cnt).*A.*B;
end % for t
S(k,l) = sum(sum(S1));
end % for l
end % for k

답변 (1개)

Ishu
Ishu 2024년 4월 4일
Hi Youngjin,
I understand that you want to use GPU computation in MATLAB. To use GPU computation you can convert your normal arrays into "gpuArray".
% converting normal arrays into gpuArray
[pY, pX] = gpuArray(meshgrid(linspace(-0.5,0.5,pnx),linspace(-0.5,0.5,pny)));
cnt_t=2601;
cnt_r=2601;
tr_x=gpuArray(linspace(-1,1,cnt_t));
tr_y=gpuArray(linspace(-1,1,cnt_t));
re_x=gpuArray(linspace(-2,2,cnt_r));
re_y=gpuArray(linspace(-2,2,cnt_r));
pza=gpuArray(linspace(0,5,101));
To further accelerate your computations you can also use "parfor" instead of normal "for" loop.
For more information on you can refer below documentation:
Hope it help!

카테고리

Help CenterFile Exchange에서 GPU Computing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by