Using parfor with a structure

1 visualizzazione (ultimi 30 giorni)
H R
H R il 27 Dic 2019
Risposto: Walter Roberson il 27 Dic 2019
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?

Risposta accettata

Walter Roberson
Walter Roberson il 27 Dic 2019
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];

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by