我正在写一个分子动力学代码,它需要使用3个函数计算3种不同类型的力,即Compute2BodyForce,Compute3BodyForce和ComputeOtherForce。
funList = {@Compute2BodyForce,@Compute3BodyForce,@ComputeOtherForce};
dataList = {data1,data2,data3}; %# or pass file names
parfor i=1:length(funList)
%# call the function
funList{i}(dataList{i});
end
其次,如何合并结果并将它们相加,即获得TotalForce = 2BodyForce + 3BodyForce + OtherForce?
发布于 2011-06-06 20:39:55
你在正确的轨道上。但是,据我所知,你不能在parfor中使用匿名函数(如果我错了,或者这只在早期版本中是正确的,对不起)。此外,您还需要有一行代码,您可以在其中打开matlab池,并通知工作节点您打算在并行部分中使用什么。这就是我开始解决这个问题的方法:
fileDep = {'Compute2BodyForce',...
'Compute3BodyForce',...
'ComputeOtherForce'};
num_procs = 3;
matlabpool('open','Mycluster',num_procs,'FileDependencies',fileDep);
parfor iter = 1:3
% iter is passed to the functions so the functions can return NaNs when we don't want computation done
body_2_dummy{iter} = Compute2BodyForce(data,iter); %assuming data is a variable here, maybe a struct that gets parsed inside the functions
body_3_dummy{iter} = Compute3BodyForce(data,iter);
other_dummy{iter} = ComputeOtherForce(data,iter);
end
% resolve and sum up here
total_force = body_2_dummy{1} + body_3_dummy{2} + other_dummy{3};
这里请注意,除了body_2_dummy{1}、body_3_dummy{2}和other_dummy{3}之外,这些函数的值应该返回NaN。这绕过了Matlab中一个令人沮丧的事情。在大多数语言中,对此进行编码的典型方法如下:
parfor iter = 1:3
if iter == 1
body_2_dummy = Compute2Body(data);
end
% more ifs for the other forces
end
在这里,我们有责任确保body_2_dummy具有明确的价值。但是在Matlab中,这个责任落在解释器身上,它不允许这样做,因为它认为body_2_dummy取决于执行的顺序。
我希望这能让你走上正确的道路。如果有任何进一步的问题,请随时回来。
此外,作为一般建议,优化函数并尝试降低其成本通常比并行化函数容易得多。您是否花过时间使用Matlab分析器中的力函数?
--安德鲁
后续编辑:
匿名函数是指当你这样做的时候:
spam = @(x) x + 2;
spam(2)
ans = 4
在这里,垃圾邮件是一个匿名函数。您可以通过传递函数句柄@spam将函数传递给另一个函数。
我使用并行计算工具箱的经验主要是与Sbiotoolbox结合使用的。在这个工具箱中,生物模型是对象,可以通过句柄引用传递,这种方式基于Matlab的句柄图形的旧版本。然而,问题是句柄从模型中分离出来,并且发生了一系列令人困惑的错误。由于这个原因,在使用Matlab的并行功能时,我避免了所有的句柄引用。
然而,我必须承认,我没有测试匿名函数是否可用,因为有一些关于本地和远程Matlab工作者的更多细节给出了一个严格的答案。目前,我无法轻松访问远程Matlab集群,因此必须将其放在项目列表中。
Matlab profiler是Matlab附带的工具。它允许你放入一个函数,并测量每一行代码所花费的时间,这样你就可以突出显示你需要重构代码以提高速度的地方。它特别擅长查找错误,比如在循环中改变数组的大小,这会消耗Matlab的性能。
我建议您在Matlab帮助中搜索“profiler”。文档非常好,而且比我在这里放的任何东西都要完整得多。
祝你好运。
https://stackoverflow.com/questions/6248439
复制相似问题