Change code to paralle computing (for loop -> parfor loop)

1 view (last 30 days)
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));
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);
ft_mcd(k,:) = temp_ft_mcd(k,:);

Accepted Answer

Walter Roberson
Walter Roberson on 10 Jun 2022
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

More Answers (0)


Find more on Loops and Conditional Statements in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!

Translated by