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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by