【问题标题】:Execute multiple functions in parfor在 parfor 中执行多个函数
【发布时间】:2012-04-10 08:01:36
【问题描述】:

目前我有几个函数,命名为function1.mfunction2.mfunction3.m、...、function10.m。每个功能都是相互独立的。我想在一次执行中运行所有功能

目前,我的代码是这样的,它一个一个地运行函数。

for i = 1 : 10
  result = eval(sprintf('function%d.m',i));
  fprintf('%d ', result);
end

我想知道有没有办法在parfor 中重写代码而不是for,因为我知道evalparfor 中不起作用。

【问题讨论】:

    标签: multithreading matlab parallel-processing parfor


    【解决方案1】:

    在正常循环中使用eval 来填充函数句柄的元胞数组?

    functions = cell(10, 1);
    for i=1:10
      functions{i} = eval(sprintf('@()function%d', i));
    end
    parfor i=1:10
      result = functions{i}();
      ...
    end
    

    【讨论】:

      【解决方案2】:

      您根本不需要使用eval 来使用forparfor 循环创建函数句柄元胞数组。那么你需要做的就是调用存储在functions单元格数组中的每个函数句柄。

      functions = cell(1, 10);
      
      parfor i = 1:10
          functions{i} = str2func([ 'function', num2str(i) ]);
      end
      
      parfor i = 1:10
          result = functions{i}();
          fprintf('%d ', result);
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-19
        相关资源
        最近更新 更多