Change code to paralle computing (for loop -> parfor loop)
2 次查看(过去 30 天)
显示 更早的评论
Hi
I am trying to change a code that has double for loop to parfor loop(outside for becomes parfor).
But it seems fall in endless loop,because simple double for loop ends almost 300 sec but parfor and inner for loop does not end when elapsed 1000 sec over.
please find my error in my code below.
Thank you.
original code
ft_mcd = zeros(npulse,nrbin);
for k=1:npulse
R_real = R_ori + R_ori .* (1-D_fa_rcmc(k,:)) ./ D_fa_rcmc(k,:);
z = fft(ft_rcd(k,:));
zp = [z(1:half_len) zeros(1, zpadlen) z(half_len+1:end)];
tf_sub = ifft(zp) * m;
tf_sub= [tf_sub tf_sub(1, end:-1:1)];
idx = round((R_real-R_ori)/ori_sam_dist*m);
for rn=1:nrbin
ft_mcd(k,rn) = tf_sub(1, 1 + m*(rn-1) + idx(rn));
end
end
%
parfor code
ft_mcd = zeros(npulse,nrbin);
parfor k = 1:npulse
temp_k = k;
temp_D_fa_rcmc = D_fa_rcmc;
temp_ft_rcd = ft_rcd;
R_real = R_ori + R_ori .* (1 - temp_D_fa_rcmc(temp_k,:)) ./ temp_D_fa_rcmc(temp_k,:);
z = fft(temp_ft_rcd(temp_k,:));
zp = [z(1:half_len) zeros(1, zpadlen) z(half_len + 1:end)];
tf_sub = ifft(zp) * m;
tf_sub2 = [tf_sub tf_sub(1, end:-1:1)];
idx = round((R_real-R_ori)/ori_sam_dist*m);
temp_ft_mcd = zeros(npulse,nrbin);
for rn=1:nrbin
temp_rn = rn;
temp_index = 1 + m*(temp_rn-1) + idx(temp_rn);
temp_ft_mcd(temp_k,temp_rn) = tf_sub2(1, temp_index);
end
ft_mcd(k,:) = temp_ft_mcd(k,:);
end
0 个评论
采纳的回答
Walter Roberson
2022-6-10
temp_ft_mcd = zeros(npulse,nrbin);
No, do not do that within the parfor. You rebuild the entire matrix each time, but you only use one row out of it. Instead
temp_ft_mcd = zeros(1,nrbin);
and use 1 for the first index, not k or temp_k
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!