Speed up nested loops with parfor
7 Comments
Hi @Alessandro Maria Marco,
Below is a refactored version of your function that incorporates these suggestions:
function F = f_ReturnFn(aprime, a, z, K_to_L, alpha, delta, pen, gamma, crra)
% Check if inputs are scalar or vector
isScalar = @(x) isscalar(x);
% Initialize F with -inf for all entries
F = -inf(size(aprime)); % Make sure F has the same size as aprime
% Calculate common parameters
r = alpha * K_to_L^(alpha - 1) - delta;
w = (1 - alpha) * K_to_L^alpha;
income = w .* z + r .* a; % Element-wise multiplication
% Budget constraint calculation
% Ensure this handles array operations correctly
c = income + a - aprime;
% Compute utility only where c > 0
validIndices = c > 0; % Logical array indicating valid consumption
if any(validIndices)
% Use element-wise operations for valid indices
F(validIndices) = c(validIndices).^(1 - crra) / (1 - crra);
if crra == 1
% Handle CRRA=1 case separately
F(validIndices) = log(c(validIndices));
end
end
end
Explanation of Changes: The modify code now incorporates the use of `.*` so that multiplications are applied element-wise across arrays.By creating a logical index array (`validIndices`), conditions can be applied directly to the output array `F`, allowing for efficient computation without separate handling for scalars and vectors and special cases like `crra = 1` are handled separately within the same function scope. Also, if you are interested, MATLAB provides functions such as `gpuArray` that can convert regular arrays into GPU-compatible arrays easily. Utilizing these functions in your code will optimize performance further. Fore more information on this function, please refer to
https://www.mathworks.com/help/parallel-computing/gpuarray.html
Please let me know if you have any further questions.
Answers (0)
See Also
Categories
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!