parfor和处理类 [英] parfor and handle classes

查看:77
本文介绍了parfor和处理类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个句柄类:

classdef A<handle


    properties
        a;
    end

    methods
        function obj = A(a)
            obj.a=a;
        end
    end
end

我有一个A个对象的单元格数组:

And I have a cell array of A objects:

arr={};
for i=1:3
    arr{i}=A(i);
end

我想做的是将该单元格数组传递到parfor循环,以便每个对象的值都将改变:

What I would like to do is pass that cell array to a parfor loop so that each object's value will change:

parfor i=1:3
    arr{i}.a=i*5;
end

但是,此代码完全不会更改arr.实际上,此处指出

However, this code does not change arr at all. Indeed, here it states that

在循环迭代过程中对工作器上的类进行处理的更改不会自动传播到客户端.

Changes made to handle classes on the workers during loop iterations are not automatically propagated to the client.

我该如何克服?

推荐答案

一个有趣的问题;我实际上从未遇到过这个问题.知道有关parfor限制的所有信息总是很高兴,所以我做了一些googlin'并提出了:

An interesting question; I actually never encountered this problem. It's always good to know everything about parfor limitations, so I did some googlin' and came up with this:

我已收到技术支持对此问题的解答. 显然,Mathworks将其视为改变为 对象不返回-尽管我看不到它非常有用 特征.无论如何,返回修改后的类属性的方法 从parfor循环中进行显式更改可以 被parfor认可.这是两个适用于上述情况的示例 示例对象:

I have received an answer to this issue from technical support. Apparently the Mathworks regard it as a 'feature' that changes to objects are not returned - though I can't see that it's a very useful feature. Anyway, the way to get modified class properties returned from a parfor loop is to make an explicit change which can be recognised by parfor. Here are two examples which work for the above example object:

parfor n = 1:num
    exArray(n).data = n:n+5;
end

parfor n = 1:num
    temp = exArray(n);
    setData(temp,n:n+5);
    exArray(n) = temp;
end

实际上,如果更改任何对象属性,它似乎也可以工作.所以 例如,如果还有第二个属性data2 显式设置,则正确返回data和data2:

Actually, if you change any object property it also seems to work. So for example this also works, if there is a second property data2 which is set explicitly, both data and data2 are correctly returned:

  parfor n = 1:num
      setData(exArray(n),n:n+5);
      exArray(n).data2 = n:n+5;
  end

示例对象由

classdef Example < handle

    properties
        data
    end

    methods
        function obj = Example(data)
            obj.data = data;
        end

        function setData(obj,data)
            obj.data = data;
        end

        function data = getData(obj)
            data = obj.data;
        end
    end
end

并将数组初始化为

% Initialise array of objects
for n = 1:num
    exArray(n) = Example(zeros(1,6));
end

这篇关于parfor和处理类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆