Evaluate Functions in the Background Using parfeval
This example shows how to solve a simple optimization problem by using parfeval
to evaluate functions in the background. You can collect the results as they become available and break out of the optimization loop early when the result is good enough.
To reproduce the same computations later, seed the random generator with the default value.
rng('default')
The objective function objFun
takes a row vector x
as input and returns a scalar value representing the objective function. Define the objective function and the number of iterations for the optimization loop. Randomly generate candidates for the x
values to evaluate the objective function. Initialize the minimum value and index variables.
objFun = @(x) x(1)^2 + x(2)^2; numIterations = 500; xCandidates = rand(numIterations,2); minFval = inf; minIndex = inf;
Use parfeval
to evaluate the objective function for each set of x
candidates in the background. For efficiency, preallocate an array of future objects.
futures(1:numIterations) = parallel.FevalFuture; for i = 1:numIterations futures(i) = parfeval(objFun,1,xCandidates(i,:)); end
Starting parallel pool (parpool) using the 'Processes' profile ... Connected to parallel pool with 6 workers.
Fetch the results as they become available and update the minimum function value and index if a new minimum is found. Break out of the loop early if the minimum value is below a certain threshold.
for idx = 1:numIterations [completedIndex, fval] = fetchNext(futures); if fval < minFval minFval = fval; minIndex = completedIndex; end if minFval <= 0.01 fprintf("Minimum found at x = [%f,%f]\n", ... xCandidates(minIndex,1),xCandidates(minIndex,2)); break; end end
Minimum found at x = [0.031833,0.093820]
Cancel any remaining futures.
cancel(futures);
clear futures;
Display the best solution found.
fprintf("Best solution found: x = [%f,%f], fval = %f\n", ... xCandidates(minIndex,1),xCandidates(minIndex,2),minFval);
Best solution found: x = [0.031833,0.093820], fval = 0.009816