Using parfor with a structure

조회 수: 1 (최근 30일)
H R
H R 2019년 12월 27일
답변: Walter Roberson 2019년 12월 27일
Hi All. I have a qyucik question on the use of parfor and an structure:
A code I have runs perfectly with for loop as follows:
Ps=[100:3.447:1000];
Ps(end)=PU;
P_V=[];
for j=1:length(Ps)
Mstructure.p=Ps(j);
[V] =f(Mstructure);
P_V=[P_V; Ps(j) V];
end
Mstructure is a structure with sevral fields. I would like to only update one of the fileds of Mstructure within a loop. Function f uses the Mstructure and calculate V. When I change this to parfor there is an error that parfor cannot be used because the way that Mstrycture is defined.
Could you please help resolve this issue?

채택된 답변

Walter Roberson
Walter Roberson 2019년 12월 27일
Experiment with
Ps=[100:3.447:1000];
Ps(end)=PU;
P_V=[];
parfor j=1:length(Ps)
MsC = Mstructure;
MsC.p=Ps(j);
[V] =f(MsC);
P_V=[P_V; Ps(j) V];
end
That should get rid of the error about the way Mstructure is defined.
However, you will still have problems.
Remember that parfor explicitly does not execute the iterations in strictly increasing order, so iteration #262 will almost certainly run before iteration #1 does. That is a problem for you because you are trying to append results on to the end of P_V in the order the results are produced, but the order is going to be irregular.
You indicate that your existing code works as a loop. It can only work if the value returned by f is a scalar or row vector. If the length of results expected is L, then change
P_V=[];
to
P_V = zeros(length(Ps), L);
and change
P_V=[P_V; Ps(j) V];
to
P_V(j, :) = [Ps(j), V];

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by