Overload operator doesn't work into workers
이전 댓글 표시
I overloaded the plus operator for my class, but it doesn't work into parfor loop. The error is the following
Error using + (line 32)
Dot indexing is not supported for variables of this type.
Function is the following
function this = plus(this, offspring)
this.Individuals(end+1:end+numel(offspring.Individuals)) = offspring.Individuals;
end
Why it doesn't work in the parfor but work correctly in the for loop?
댓글 수: 1
Andrea Stevanato
2018년 6월 25일
편집: Andrea Stevanato
2018년 6월 25일
답변 (2개)
Sayyed Ahmad
2018년 6월 26일
class handel is a pointer of Memory. To better understand try this codes
a = ClassA(10);
b = ClassB(a);
a.value
b.a.value
a.value=20
b.a.value
so you Change in each time the value in the same Memory. if you did not useing of handle class your code will work.
댓글 수: 1
Andrea Stevanato
2018년 6월 26일
Guillaume
2018년 6월 26일
I don't know the reason for the particular error you get but you will always get an error anyway since your code is not parallelisable. You're growing an array by an arbitrary size at each step of the loop. In a parfor loop all steps of the loop occur at the same time, hence you would be growing the same array in parallel without anyway to reconcile all the grown arrays:
- for loop
i = 1:
b.a = [b.a a(1)]
i = 2:
b.a = [b.a a(1) a(2)]
i = 3:
b.a = [b.a a(1) a(2) a(3)]
- parfor
i = 1 i = 2 i = 3
b.a = [b.a a(1)] b.a = [b.a a(2)] b.a = [b.a a(3)
put together: b.a = ????
댓글 수: 2
Andrea Stevanato
2018년 6월 26일
편집: Andrea Stevanato
2018년 6월 26일
with arbitrary order
That may be what you want but that's not the way parfor works. parfor, as designed, is not capable to paralellise your code (with or without handle). You cannot have parallel branches growing the same array at once.
What may work (completely untested, don't have the toolbox):
classdef classB < handle
properties
a;
accum = {};
end
methods
function this = classB(A, accumsize)
this.a = A.value;
this.accum = cell(1, accumsize);
end
function add(this, A, idx)
this.accum{idx} = A.value;
end
function result = gather(this)
result = [this.a, this.accum{:}];
end
end
end
a = classA(10);
numadds = 3
b = classB(a, numadds);
parfor i = 1:numadds
b.add(a, i);
end
b.gather
카테고리
도움말 센터 및 File Exchange에서 Parallel for-Loops (parfor)에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!