我对MATLAB中的并行计算很新,我面临以下问题:我有以下脚本迭代调用优化函数
trials = cell2struct([ ...
{ 4 5 6 7 10 16 17 18 23 24}; ...
{ 0.5 1 0.5 0 0 0.5 0.5 0.5 0.5 0}; ...
{ 0 0 pi pi 0 pi-pi/6 -pi/6 pi/6 pi+pi/6 pi/6}; ...
{0.0458 0.0440 0.0510 0.0312 0.0464 0.0449 0.0461 0.0598 0.0598 0.0511} ], ...
{'idx', 'mounting', 'q5_0', 'dq4_squared'}, 1);
coeff = [2, 10.5, 20, 25, 2.5];
while < some_stop_condition >
[coeff, fval] = fminunc(@(x) EvaluateIndex(x, trials), coeff);
end
我有一个函数EvaluateIndex
的工作顺序版本,但由于执行计算需要很长时间,所以我想切换到并行版本。 “并行化”目标函数EvaluateIndex
的简化版如下:
function MeanSquaredError = EvaluateIndex(coeff, configs)
% Simulation time
dT = 0.01; % Time step [s]
T_final = 60; % Duration [s]
% Wave characteristics
wave = SeaWave( < sea_wave_params > );
% Vehicle settings
for i = 1:length(configs)
vehicle(i) = PrototypeWAVE( < vehicle_i_params > );
end
dq4_squared = zeros(1, length(configs));
tic
parfor i = 1:length(configs)
% Initial conditions
q1_0 = 0;
q2_0 = 0;
q3_0 = 0;
q4_0 = pi/2;
q5_0 = configs(i).q5_0;
q_0 = [ q1_0+1.3*(1-cos(q3_0)), q2_0+1.3*sin(q3_0), q3_0, q4_0, q5_0 ]';
dq_0 = [ 0, 0, 0, 0, 0 ]';
% Run simulation
[~, Results] = Run(vehicle(i), wave, [q_0; dq_0], dT, T_final);
% Get results
dq4_squared(i) = mean(Results(:,9).^2);
end
toc
MeanSquaredError = sum( (dq4_squared - horzcat(configs.dq4_squared)).^2 );
end
此处,SeaWave
和PrototypeWAVE
是两个类,函数Run
是PrototypeWAVE
类的方法。根据我发现的一些建议,我在parfor
循环之外定义了这些类的对象;但是,当我尝试运行脚本时,我收到以下警告:
Warning: Element(s) of class 'SeaWave' do not match the current constructor definition. The element(s) have been converted to structures.
Warning: Element(s) of class 'PrototypeWAVE' do not match the current constructor definition. The element(s) have been converted to structures.
并出现此错误:
Error using EvaluateIndex (line 75)
Cannot find an exact (case-sensitive) match for 'Run'
The closest match is: run in /Applications/MATLAB_R2016b.app/toolbox/matlab/lang/run.m
似乎MATLAB无法识别类及其方法的存在。我已经尝试在addAttachedFiles(gcp, {'./@SeaWave', './@PrototypeWAVE'})
循环之前添加行parfor
,但没有任何变化。
我在MACOS上使用MATLAB R2016b。
非常感谢任何帮助。提前致谢