Using parfor with a structure
4 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
Walter Roberson
on 27 Dec 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];
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!