Finding minimum value using parfor
显示 更早的评论
I am trying to find the minimum value of function I have made. The function has 12 parameters.
I have used fminsearch and globalsearch but it does not seem to find the best result, so the full-search running multiple for-loops is being tried.
The form was simple but takes extremely long time that I had to try using parfor.
The problem is that I have trouble in using parallel computng with variables.
This is the basic form of my code
%Assuming that I am trying to find the minimum value for functionA(x1,x2,x3,x4,....,x12)
min_error=10000;
parfor x1=lb_x1:ub_x1
for x2=lb_x2:ub_x2
for x3=lb_x3:ub_x3
...
for x12=lb_x12:ub_x12
temp=functionA(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12);
if min_error > temp
min_error=temp;
minX=[x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12];
end
end
...
end
end
end
The error comes out that it cannot access to the outer variable.
So I tried other approaches like initializing the variable inside when it does not exist, but then the parallel loop cause error in exist function.
if exist('min_error','var')
if min_error > temp
min_error=temp;
minX=[x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12];
end
else
min_error=10000;
end
Do you how to search for minimum value inside the parfor loop?
Thank you
回答(1 个)
Walter Roberson
2019-1-25
%Assuming that I am trying to find the minimum value for functionA(x1,x2,x3,x4,....,x12)
x1_vals = lb_x1 : ub_x1;
num_x1 = length(x1_vals);
min_error = zeros(num_x, 1);
minX = nan(num_x1, 12);
parfor x1idx = 1 : num_x1;
x1 = x1_vals(x1idx);
local_min_error = 10000;
local_minX = nan(1,12);
for x2=lb_x2:ub_x2
for x3=lb_x3:ub_x3
...
for x12=lb_x12:ub_x12
temp=functionA(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12);
if temp < local_min_error
local_min_error=temp;
local_minX=[x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12];
end
end
...
end
end
min_error(x1idx) = local_min_error;
minX(x1idx, :) = local_minX;
end
bestmin = min(min_error);
minX = minX(min_error == bestmin, :);
min_error = bestmin;
However really this should be further improved to take into account that multiple configurations might result in the same min.
类别
在 帮助中心 和 File Exchange 中查找有关 Parallel Computing Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!