gpt4 book ai didi

matlab - parfor 和句柄类

转载 作者:太空宇宙 更新时间:2023-11-03 19:34:23 29 4
gpt4 key购买 nike

我有一个句柄类:

classdef A<handle


properties
a;
end

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

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

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

我想做的是将该元胞数组传递给 parfor 循环,以便每个对象的值都会发生变化:

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

然而,这段代码根本没有改变arr。事实上,here它指出

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

我怎样才能克服这个问题?

最佳答案

一个有趣的问题;我实际上从未遇到过这个问题。了解关于 parfor 限制的一切总是好的,所以我做了一些谷歌搜索并想出了 this :

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

or

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

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

关于matlab - parfor 和句柄类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12200236/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com