Vectorize a nested loop
Show older comments
Hi all,
is there a way to vectorize the following loop?
for RIPETIZIONE = 1:10
%for k = 1:size(lambda_tol_vector.Value,1)
parfor (k = 1:size(lambda_tol_vector.Value,1))
%fprintf('Completion using nuclear norm regularization... \n');
[CompletedMat,flag] = matrix_completion_nuclear_GG_vec( ...
A.Value.*double(B), double(B), N, lambda_tol_vector.Value(k), tol);
if flag==1
CompletedMat_parvec{RIPETIZIONE,k}=zeros(size(A));
end
CompletedMat_parvec{RIPETIZIONE,k}=CompletedMat;
end
end
5 Comments
Move the PARFOR loops outside. Starting a parallel loop inside another loop is expensive.
The main part happens inside matrix_completion_nuclear_GG_vec(), so post this code instead of the outer loops.
What are the input values? If B is a large array, creating a copy in double format can be expensive already. Then doing this once only can increase the speed already. A.Value.*double(B) is a constand also. So do not claculate it repeatedly, but once before the loops.
What is the purpose of checking the values of flag?
if flag==1
CompletedMat_parvec{RIPETIZIONE,k}=zeros(size(A));
end
CompletedMat_parvec{RIPETIZIONE,k}=CompletedMat;
This wasted time only, because if flag equals 1, the output is filled by a zero array, but overwritten directly. Maybe you want:
if flag==1
CompletedMat_parvec{RIPETIZIONE,k}=zeros(size(A));
else
CompletedMat_parvec{RIPETIZIONE,k}=CompletedMat;
end
If CompletedMat_parvec pre-allocated?
federico nutarelli
on 28 Nov 2022
Edited: federico nutarelli
on 28 Nov 2022
"Yes CompletedMat_parvec is pre-allocated as a cell array: CompletedMat_parvec={};" - This is not a pre-allocation. Pre-allocating means, to create the array with the final size instead of letting it grow iteratively.
I do not find the code of matrix_completion_nuclear_GG_vec in the other thread, but only matrix_completion_nuclear_GG_alt. Please do not let the readers guess, which code you are using.
By the way, avoid overdoing when naming functions. Too long functions names let you loose the overview.
federico nutarelli
on 28 Nov 2022
Edited: federico nutarelli
on 28 Nov 2022
federico nutarelli
on 28 Nov 2022
Accepted Answer
More Answers (0)
Categories
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!