文档

编写任务功能

在此示例中,我们查看了两个常见的情况,当我们可能想为并行计算工具箱™编写包装函数时。这些包装器功能将是我们的任务功能,并允许我们以有效的方式使用工具箱。特定情况是:

  • 我们希望一个任务包括多次调用非矢量化函数。

  • 我们想减少任务返回的数据量。

先决条件:

要进一步阅读,请参见:

在任务中多次调用非矢量函数

将MATLAB®计算分为任务示例讨论了构建大量任务仅执行少量工作的大量任务的效率低下。相反,每个任务都应执行合理的工作,以使任务的开销不会使其运行时间缩短。因此,我们经常发现自己处于每个任务应执行以下操作的情况下:

Given a vectorX,返回向量y这样y(i)= f(x(i))。If the functionF被矢量化,MATLAB语句y = f(x)做到这一点,所以我们让Fbe our task function. However, ifF未经矢量化,我们必须编写一个任务功能来调用F在循环内。也就是说,我们希望任务功能看起来如下:

功能y = mytaskfnc(x)len = numel(x);y =零(1,len);为了i = 1:len y(i)= f(x(i));结尾

例如,让我们看一下从多个起点最小化Rosenbrock测试功能的问题。假设我们希望起点是形式[-D,D]我们想使用fminsearch执行最小化的方法。我们很容易到达以下任务功能:

类型pctdemo_task_tutorial_taskFunction;
函数xmin = pctdemo_task_tutorial_taskFunction(x)%pctdemo_task_tutorial_taskFunction最小化Rosenbrock函数。%xmin = pctdemo_task_tutorial_taskFunctions(x)返回通过在[-x(i),x(i)]开始找到的%rosenbrock函数的最小值。%输出向量Xmin的长度与输入向量X相同。%版权2007 The Mathworks,Inc。Xmin = Zeros(Numel(X),2);对于i = 1:numel(x)xmin(i,:) = fminsearch(@IROSENBROCK,[-X(i),x(i)]);pctdemo_task_tutorial_taskFunction的端端%端。函数y = irosenbrock(x)%众所周知的优化测试功能,rosenbrock函数。y = 100*(x(2)-x(1)^2)^2+(1-x(1))^2;结尾

我们可以创建一个由多个任务组成的作业,每个任务都可以在其中处理尽可能多的起点。

减少任务返回的数据

Our tasks might invoke some MATLAB functions that generate more data than we are interested in. Since there is considerable overhead in transmitting the return data over the network, we would like to minimize such data transfers. Thus, the task function might look something like the following:

功能d = mytaskfnc(x)%仅从f返回最后的输出参数。放弃其余的。[a, b, c, d] = f(x);

当然还有很多其他的可能性:We might want to return only the sum of a vector instead of the entire vector, the last point of a time series instead of the entire time series, etc.

这个话题有帮助吗?